Is there anyway to do the equivalent of this?
my_list = [try: my_dict["some_key"] except KeyError: 0 for my_dict in my_list]
Since dictionaries throw KeyErrors I want to catch the error if the element in the list does not have a "some_key" property. I know I could create a defaultdict by importing collections and sidestepping the exception, but I want to know if this is possible with out of the box dictionaries.
No, you can't. You can put only for
loops, if
's and else
's.
What you can do, though, is use .get()
, which never throws a KeyError:
my_list = [my_dict.get("some_key", 0) for my_dict in my_list]
The second argument is the default value in case the key does not exist. If you don't specify a default, the default default is None.
No, you can not do this directly in a list comprehension. You must factor the try/except logic out into a separate function, and then call the function.
There is an easy alternative for the use case shown in your question, though, using dict.get
:
my_list = [my_dict.get('some_key', 0) for my_dict in my_list]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With