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

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -