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)
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".
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