Can you embed a try in a Python list comprehension? -


is there anyway equivalent of this?

my_list = [try: my_dict["some_key"] except keyerror: 0 my_dict in my_list] 

since dictionaries throw keyerrors want catch error if element in list not have "some_key" property. know create defaultdict importing collections , sidestepping exception, want know if possible out of box dictionaries.

no, can't. can put for loops, if's , else's.

what can do, though, use .get(), never throws keyerror:

my_list = [my_dict.get("some_key", 0) my_dict in my_list] 

the second argument default value in case key not exist. if don't specify default, default default none.


Comments

Popular posts from this blog

'hasOwnProperty' in javascript -

python - ValueError: No axis named 1 for object type <class 'pandas.core.series.Series'> -

Command prompt result in label. Python 2.7 -