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 sea
Use .get()
with empty dictionaries as defaults:
if 'Dict4' in Dict1.get('Dict2', {}).get('Dict3', {}):
print "Yes"
If the Dict2
key is not present, an empty dictionary is returned, so the next chained .get()
will also not find Dict3
and return an empty dictionary in turn. The in
test then returns False
.
The alternative is to just catch the KeyError
:
try:
if 'Dict4' in Dict1['Dict2']['Dict3']:
print "Yes"
except KeyError:
print "Definitely no"
Here's a generalization for an arbitrary number of keys:
for Dict1 in DictionariesList:
try: # try to get the value
reduce(dict.__getitem__, ["Dict2", "Dict3", "Dict4"], Dict1)
except KeyError: # failed
continue # try the next dict
else: # success
print("Yes")
Based on Python: Change values in dict of nested dicts using items in a list.
How about a try/except block:
for Dict1 in DictionariesList:
try:
if 'Dict4' in Dict1['Dict2']['Dict3']:
print 'Yes'
except KeyError:
continue # I just chose to continue. You can do anything here though