Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you embed a try in a Python list comprehension?

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.

like image 978
CamJohnson26 Avatar asked Dec 04 '22 22:12

CamJohnson26


2 Answers

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.

like image 159
zondo Avatar answered Dec 11 '22 15:12

zondo


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]
like image 20
wim Avatar answered Dec 11 '22 16:12

wim