分配时 Python 字典键错误 - 我该如何解决这个问题?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24089383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:57:28  来源:igfitidea点击:

Python dictionary key error when assigning - how do I get around this?

pythondictionarykeyerror

提问by ulak blade

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

So when I pass myDict[2000]['hello']somewhere, it would give 50.

所以当我经过myDict[2000]['hello']某个地方时,它会给50.

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?

为什么 Python 不直接在那里创建这些条目?有什么问题?我认为 KeyError 只有在您尝试读取不存在的条目时才会发生,但我是在这里创建它?

采纳答案by OldGeeksGuide

KeyErroroccurs because you are trying to read a non-existant key when you try to access myDict[2000]. As an alternative, you could use defaultdict:

KeyError发生的原因是当您尝试访问myDict[2000]. 作为替代方案,您可以使用defaultdict

>>> from collections import defaultdict
>>> myDict = defaultdict(dict)
>>> myDict[2000]['hello'] = 50
>>> myDict[2000]
{'hello': 50}

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.

defaultdict(dict)意味着如果 myDict 遇到一个未知的键,它将返回一个默认值,在这种情况下,无论 dict() 返回的是什么,它是一个空字典。

回答by Daniel Roseman

But you aretrying to read an entry that doesn't exist: myDict[2000].

但是您正在尝试读取一个不存在的条目:myDict[2000]

The exact translation of what you say in your code is "give me the entry in myDict with the key of 2000, and store 50 against the key 'hello' in that entry." But myDict doesn't have a key of 2000, hence the error.

您在代码中所说的确切翻译是“给我 myDict 中的条目,键为 2000,并在该条目中根据键 'hello' 存储 50。” 但是 myDict 没有 2000 的键,因此出现错误。

What you actually need to do is to create that key. You can do that in one go:

您实际需要做的是创建该密钥。你可以一口气做到这一点:

myDict[2000] = {'hello': 50}

回答by Snakes and Coffee

You're right, but in your code python has to first get myDict[2000] and then do the assignment. Since that entry doesn't exist it can't assign to its elements

你是对的,但在你的代码中,python 必须首先获得 myDict[2000] 然后进行赋值。由于该条目不存在,因此无法分配给其元素

回答by Aaron Hall

What you want is to implement a nested dict:

你想要的是实现一个嵌套的 dict

I recommend this approach:

我推荐这种方法:

class Vividict(dict):
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value

From the docs, under d[key]

从文档中,在 d[key]

New in version 2.5: If a subclass of dict defines a method __missing__(), if the key keyis not present, the d[key] operation calls that method with the key key as argument

2.5 新版功能:如果 dict 的子类定义了一个 method __missing__(),如果 keykey不存在,则 d[key] 操作以 key 作为参数调用该方法

To try it:

试试看:

myDict = Vividict()

myDict[2000]['hello'] = 50

and myDict now returns:

并且 myDict 现在返回:

{2000: {'hello': 50}}

And this will work for any arbitrary depth you want:

这将适用于您想要的任何任意深度:

myDict['foo']['bar']['baz']['quux']

just works.

只是工作。