Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: check for a KeyError in a list comprehension?

Is there a way that I can write the following in a single line without causing a KeyError if entries is not present in mydict?

b = [i for i in mydict['entries'] if mydict['entries']]
like image 577
Richard Avatar asked Sep 19 '25 00:09

Richard


2 Answers

You can use dict.get() to default to an empty list if the key is missing:

b = [i for i in mydict.get('entries', [])]

In your version, the if filter only applies to each iteration as if you nested an if statement under the for loop:

for i in mydict['entries']:
    if mydict['entries']:

which isn't much use if entries throws a KeyError.

like image 193
Martijn Pieters Avatar answered Sep 20 '25 14:09

Martijn Pieters


You can try this code:

b = [i for i in mydict.get('entries', [])]
like image 38
Sharath Avatar answered Sep 20 '25 16:09

Sharath