【问题标题】:Python dictionary key error when assigning - how do I get around this?分配时出现 Python 字典键错误 - 我该如何解决?
【发布时间】:2014-07-28 04:04:21
【问题描述】:

我有一本这样创建的字典:

myDict = {}

然后我喜欢在其中添加对应于另一个字典的键,我在其中放置另一个值:

myDict[2000]['hello'] = 50

所以当我在某处传递myDict[2000]['hello'] 时,它会给出50。

为什么 Python 不直接在此处创建这些条目?有什么问题?我认为 KeyError 仅在您尝试读取不存在的条目时发生,但我正在这里创建它?

【问题讨论】:

    标签: python dictionary keyerror


    【解决方案1】:

    根据下面的场景,当你将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)
    

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 你在哪里定义了dict?还是原始人?
      • 是的,dict是内置类型。
      【解决方案3】:

      你要的是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']
      

      刚刚好。

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

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

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

          您实际需要做的是创建该密钥。您可以一次性完成:

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

          【讨论】:

          • 不过,这将丢弃 myDict[2000] 中其他键的任何现有条目。 defaultdict(dict) 可能值得考虑。
          猜你喜欢
          • 2020-10-29
          • 2023-03-08
          • 2016-06-19
          • 1970-01-01
          • 2019-06-28
          • 2020-08-18
          • 1970-01-01
          • 2018-12-25
          • 1970-01-01
          相关资源
          最近更新 更多