简体   繁体   English

Python:将列表转换为带有异常处理的多维dict的dict键

[英]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 dimensions of the dictionary. Apriori,我不知道字典的尺寸。 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 如何将列表作为键传递,以便我可以获得dict1['key21']['key32']['key42'] ,异常处理类似于get命令

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. KeyError处理密钥不存在的情况。 TypeError handles the case where the item is not a dictionary, and hence, further lookup cannot be done. TypeError处理项不是字典的情况,因此无法进行进一步查找。 This is an interesting case that's easy to miss (I did the first time). 这是一个很容易错过的有趣案例(我是第一次做的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM