Python: Convert List To Dict Keys For Multidimensional Dict With Exception Handling
I have a collection of multidimensional dictionaries that looks as follows dict1 = {'key21':{'key31': {'key41':val41}, 'key32':{'key42':val42}}} Apriori, I dont know the dimension
Solution 1:
You can query the dictionary iteratively, like this:
dict1 = {'key21':{'key31': {'key41':41}, 'key32':{'key42':42}}}
list1 = ['key21', 'key32', 'key42']
#list1 = ['key21', 'key32', 'key42', 'bad-key'] # Test bad key
item = dict1
try:
for key in list1:
item = item[key]
except (KeyError, TypeError):
print None
else:
print item
KeyError
handles the case where the key doesn't exist.
TypeError
handles the case where the item is not a dictionary, and hence, further lookup cannot be done. This is an interesting case that's easy to miss (I did the first time).
Post a Comment for "Python: Convert List To Dict Keys For Multidimensional Dict With Exception Handling"