Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ignore keyError in list list comprehension

I'm trying to extract all objects that have certain keys in a dict however some dicts do not contain all of the keys and I would like to ignore the keyError and keep going. I`ve seen some implementations of doing this with try and except but it will not work in my case

allValues = []
for dictionary in masterDict:
    values = [(dictionary[x]) for x in keysArray]
    allValues.append(values)
like image 512
loag Avatar asked Dec 10 '22 11:12

loag


1 Answers

You should use a filter statement in the list comprehension:

values = [dictionary[x] for x in keysArray if x in dictionary]

So here Python will first check if x in dictionary holds. If not, then the x is ignored. Otherwise dictionary[x] is added to the dictionary.

In case you do not want to ignore these values, but add a fallback value to the list, you can use:

values = [dictionary.get(x,fallback) for x in keysArray]

where fallback is the "fallback value".

like image 68
Willem Van Onsem Avatar answered Dec 12 '22 23:12

Willem Van Onsem