简体   繁体   English

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

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

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?为什么 Python 不直接在那里创建这些条目? 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 只有在您尝试读取不存在的条目时才会发生,但我是在这里创建它?

KeyError occurs because you are trying to read a non-existant key when you try to access myDict[2000] . KeyError发生是因为您在尝试访问myDict[2000]时试图读取不存在的密钥。 As an alternative, you could use defaultdict :作为替代方案,您可以使用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() 返回的是一个空字典。

But you are trying 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."您在代码中所说的确切翻译是“给我 myDict 中的条目,键为 2000,并在该条目中根据键 'hello' 存储 50。” But myDict doesn't have a key of 2000, hence the error.但是 myDict 没有 2000 的键,因此出现错误。

What you actually need to do is to create that key.您实际需要做的是创建该密钥。 You can do that in one go:你可以一口气做到这一点:

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

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 key is not present, the d[key] operation calls that method with the key key as argument 2.5 新版功能:如果 dict 的子类定义了一个方法__missing__() ,如果 key key不存在,则 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.只是工作。

You're right, but in your code python has to first get myDict[2000] and then do the assignment.你是对的,但在你的代码中,python 必须首先获得 myDict[2000] 然后进行赋值。 Since that entry doesn't exist it can't assign to its elements由于该条目不存在,因此无法分配给其元素

According to the below scenario, when you append type new_result into dict , you will get KeyError: 'result'根据以下场景,当您将type new_result附加到dict ,您将收到KeyError: 'result'

    dict = {}
    new_result = {'key1':'new_value1','key2':'new_value'}
    dict['result'].append(new_result)

Because key doesn't exist in other words your dict doesn't have a result key.因为键不存在,换句话说你的dict没有结果键。 I fixed this problem with defaultdict and their setdefault method.我用defaultdict和他们的setdefault方法解决了这个问题。

To try it;尝试一下;

    from collections import defaultdict
    dict = defaultdict(dict)
    new_result = {'key1':'new_value1','key2':'new_value2'}
    dict.setdefault('result', []).append(new_result)

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

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