For a large list of nested dictionaries, I want to check if they contain or not a key. Each of them may or may not have one of the nested dictionaries, so if I loop this search through all of them raises an error:
for Dict1 in DictionariesList:
if "Dict4" in Dict1['Dict2']['Dict3']:
print "Yes"
My solution so far is:
for Dict1 in DictionariesList:
if "Dict2" in Dict1:
if "Dict3" in Dict1['Dict2']:
if "Dict4" in Dict1['Dict2']['Dict3']:
print "Yes"
But this is a headache, ugly, and probably not very resources effective. Which would be the correct way to do this in the first type fashion, but without raising an error when the dictionary doesnt exist?
How about a try/except block:
Here's a generalization for an arbitrary number of keys:
Based on Python: Change values in dict of nested dicts using items in a list.
Use
.get()
with empty dictionaries as defaults:If the
Dict2
key is not present, an empty dictionary is returned, so the next chained.get()
will also not findDict3
and return an empty dictionary in turn. Thein
test then returnsFalse
.The alternative is to just catch the
KeyError
: