问题描述
我收集了多维字典,如下所示:
I have a collection of multidimensional dictionaries that looks as follows
dict1 = {'key21':{'key31': {'key41':val41}, 'key32':{'key42':val42}}}
Apriori,我不知道字典的尺寸。我有一大堆可能的键,每个字典可能包含或可能不包含键。即使存在,密钥可能不一定是相同的顺序。
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']
如何将列表作为关键字,以便我可以获取 dict1 ['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
推荐答案
您可以这样迭代地查询字典:
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
处理键不存在的情况。
TypeError
处理项目不是字典的情况,因此无法进行进一步的查找。这是一个有趣的情况,很容易错过(我第一次做到)。
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).
这篇关于Python:将列表转换为具有异常处理的多维dict的dict键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!