在Python3中使用枚举作为字典键时出现“键错误”

2024-04-18 17:34:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用枚举作为字典的键,但得到了一个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表示我可以使用任何不可变的值作为键,并且我假设枚举值是不可变的。你知道吗

如何使用枚举作为字典中的键?你知道吗


Tags: infromimport字典greenenumbluered