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

时间:2014-06-06 19:33:39

标签: python dictionary keyerror

我有一个我这样创建的词典:

myDict = {}

然后我想在其中添加与另一个字典相对应的键,其中我放了另一个值:

myDict[2000]['hello'] = 50

因此,当我在某处传递myDict[2000]['hello']时,它会给50

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

5 个答案:

答案 0 :(得分:21)

发生

KeyError是因为您在尝试访问myDict[2000]时尝试读取不存在的密钥。作为替代方案,您可以使用defaultdict

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

defaultdict(dict)表示如果myDict遇到一个未知密钥,它将返回一个默认值,在这种情况下,dict()返回的是一个空字典。

答案 1 :(得分:7)

试图读取不存在的条目:myDict[2000]

你在代码中所说内容的确切翻译是“在myDict中输入密钥为2000的条目,并在该条目中将密钥'hello'存储为50。”但myDict没有2000的密钥,因此错误。

您实际需要做的是创建该密钥。你可以一气呵成:

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

答案 2 :(得分:4)

你想要的是implement a nested dict

我推荐这种方法:

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

从文档中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

试一试:

myDict = Vividict()

myDict[2000]['hello'] = 50

并且myDict现在返回:

{2000: {'hello': 50}}

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

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

正常工作。

答案 3 :(得分:2)

根据以下场景,当您将 type new_result 附加到 dict 中时,您将得到 KeyError: 'result'

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

因为键不存在,换句话说,您的 dict 没有结果键。我用 defaultdict 和他们的 setdefault 方法解决了这个问题。

尝试一下;

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

答案 4 :(得分:1)

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