You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中使用枚举(Enum)索引字符串键的字典?

解决办法

方法1:使用StrEnum(Python 3.11及以上)

直接让枚举类继承StrEnum,它会自动让枚举实例表现得像字符串,无需额外处理就能匹配字典中的字符串键:

from enum import StrEnum

class STATUS(StrEnum):
    ACTIVE = "active"

d = { "active": 1 }
print(d[STATUS.ACTIVE])  # 输出 1

方法2:重写__hash__和__eq__方法(兼容旧Python版本)

如果使用Python 3.10及以下版本,手动重写枚举类的哈希和相等性判定方法,让枚举实例的哈希值和比较逻辑基于其value属性:

from enum import Enum

class STATUS(Enum):
    ACTIVE = "active"

    def __hash__(self):
        return hash(self.value)
    
    def __eq__(self, other):
        if isinstance(other, str):
            return self.value == other
        return super().__eq__(other)

d = { "active": 1 }
print(d[STATUS.ACTIVE])  # 输出 1

原理

字典查找时会先计算键的哈希值,再做相等性校验。重写__hash__让枚举实例的哈希值与对应字符串的哈希值一致,重写__eq__让枚举实例能直接和字符串做值比较,这样就能匹配到字典里的字符串键。

内容的提问来源于stack exchange,提问作者alps

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 18:40:44