【问题标题】:"key error" when using an enum as a dictionary key in Python3在 Python3 中使用枚举作为字典键时出现“键错误”
【发布时间】:2019-09-23 00:16:27
【问题描述】:

我想使用枚举作为字典的键,但得到一个 KeyError。

#!/usr/bin/python3

from enum import Enum, unique
from typing import List

@unique
class Color(Enum):
    RED = "cherry"
    GREEN = "cucumber"
    BLUE = "blueberry"

allColors = {}

def countColors(colors: List[Color]):
    for c in colors:
        allColors[c] += 1

countColors([Color.RED, Color.RED, Color.BLUE, Color.GREEN])
for c in allColors:
    print(f"""{allColors[c]} {c.value} {c.name} pipes""")

当我运行它时,我得到了

Traceback (most recent call last):
  File "mvce.py", line 18, in <module>
    countColors([Color.RED, Color.RED, Color.BLUE, Color.GREEN])
  File "mvce.py", line 16, in countColors
    allColors[c] += 1
KeyError: <Color.RED: 'cherry'>

documentation on dictionaries 说我可以使用任何不可变值作为键,并且我假设枚举值是不可变的。

如何使用枚举作为字典中的键?

【问题讨论】:

  • allColors[c] += 1 要求 c 是一个已存在的密钥。您可能需要一个 if 条件。
  • 使用任何其他有效键类型(如整数或字符串)都会遇到完全相同的问题。
  • @Sraw 是的,就是这样。我假设 Python 会像 Perl 一样自动创建目录条目。首先检查它,然后将其设置为 0 或增加它可以解决问题。如果您想将此作为答案发布,我很乐意接受。
  • 有一个名为 defaultdict 的库包,它允许您定义一个字典,其中包含要返回的默认值,而不是引发 KeyError。

标签: python python-3.x dictionary enums


【解决方案1】:

可能是您设置了 3 种颜色,但在第 18 行中您设置了 4 种颜色

countColors([Color.RED, Color.RED, Color.BLUE, Color.GREEN])

试试

countColors ([Color.RED, Color.Blue, Color.Green])

【讨论】:

  • 嗯,是的,我想计算我获得每种颜色的频率,所以这是故意的。
  • 现在我跟着你 Ethan。
猜你喜欢
  • 2019-06-29
  • 1970-01-01
  • 1970-01-01
  • 2011-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-30
  • 1970-01-01
相关资源
最近更新 更多