1

I have a collection of multidimensional dictionaries that looks as follows

dict1 = {'key21':{'key31': {'key41':val41}, 'key32':{'key42':val42}}}

Apriori, I dont know the dimensions of the dictionary. I have a huge collection of possible keys and each dictionary might or might not contain the keys. Even if present, the keys may not have to be in the same order.

If I create a list of possible key values from the collection, say

list1 = ['key21', 'key32', 'key42']

How can I pass the list as key so that I can get the value of dict1['key21']['key32']['key42'] with exception handling similar to get command

rambalachandran
  • 2,091
  • 2
  • 19
  • 34

1 Answers1

3

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

th3an0maly
  • 3,360
  • 8
  • 33
  • 54
  • Why not just `item = dict1[list1[0]][list1[1]][list1[2]]` inside a `try`? – martineau Apr 12 '16 at 20:10
  • According to the OP; "Apriori, I neither know the dimensions of the dictionary nor the key-values". – th3an0maly Apr 12 '16 at 20:11
  • It works fine if the depth of the key is same as that of dictionary. You need to add an except for `TypeError` when the keylist length is longer than the dimensionality of the dict – rambalachandran Apr 12 '16 at 20:13
  • Maybe he gets it from the user, or even from a file. – th3an0maly Apr 12 '16 at 20:13
  • Then the source of the keys somehow "knows"? – martineau Apr 12 '16 at 20:14
  • Sorry I should have been more precise. I have a huge collection of possible key values to try on the dictionary and each individual dictionary might or might not have all the keys, and if present might not have to be in the same order. – rambalachandran Apr 12 '16 at 20:16