问题描述
我有一个这样创建的字典:
I have a dictionary that I create like this:
myDict = {}
然后我想在其中添加与另一个字典相对应的键,在其中我输入另一个值:
Then I like to add key in it that corresponds to another dictionary, in which I put another value:
myDict[2000]['hello'] = 50
所以当我将myDict[2000]['hello']
传递到某个地方时,它将给出50
.
So when I pass myDict[2000]['hello']
somewhere, it would give 50
.
为什么Python不只是在此处创建这些条目?有什么问题我以为KeyError仅在您尝试读取不存在的条目时才会发生,但我是在这里创建它的?
Why isn't Python just creating those entries right there? What's the issue? I thought KeyError only occurs when you try to read an entry that doesn't exist, but I'm creating it right here?
推荐答案
KeyError
的原因是,当您尝试访问myDict[2000]
时试图读取不存在的密钥.或者,您可以使用 defaultdict :
KeyError
occurs because you are trying to read a non-existant key when you try to access myDict[2000]
. As an alternative, you could use defaultdict:
>>> from collections import defaultdict
>>> myDict = defaultdict(dict)
>>> myDict[2000]['hello'] = 50
>>> myDict[2000]
{'hello': 50}
defaultdict(dict)
意味着,如果myDict遇到未知密钥,它将返回默认值,在这种情况下,由dict()返回的内容是空字典.
defaultdict(dict)
means that if myDict encounters an unknown key, it will return a default value, in this case whatever is returned by dict() which is an empty dictionary.
这篇关于分配时发生Python字典键错误-我该如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!