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']]
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
.
You can try this code:
b = [i for i in mydict.get('entries', [])]
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