Python: Convert list to dict keys for multidimensi

2019-07-27 06:41发布

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

1条回答
倾城 Initia
2楼-- · 2019-07-27 07:13

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

查看更多
登录 后发表回答