Python中如何实现对键类型敏感的字典?
问题背景
Python 3能区分1和1.0的类型:
>>> type(1) <class 'int'> >>> type(1.0) <class 'float'>
但普通字典中,二者作为键会被视为同一个(原因是hash(1)和hash(1.0)的结果均为1):
>>> {1: 'one', 1.0: 'one point zero'} {1: 'one point zero'}
需求
需要一个类字典对象my_dict,实现如下效果:
>>> my_dict {1: 'one', 1.0: 'one point zero'} >>> my_dict[1] 'one' >>> my_dict[1.0] 'one point zero'
疑问
是否存在对键类型敏感的dict子类?若没有,是否需要自定义子类并重写__init__、__getitem__、__setitem__和update方法?我设想用(type(key), key)作为内部存储的键。
补充说明
我需要这类字典的原因是定义了AutoEnum类:
from enum import IntEnum, auto class AutoEnum(IntEnum): def _generate_next_value_(self, _start, count, _last_values): return count
通过该类可定义自动赋值的枚举类,成员值从0开始依次递增:
class Fruit(AutoEnum): apple = auto() # 0 pear = auto() # 1 banana = auto() # 2 orange = auto() # 3 class Animal(AutoEnum): cat = auto() # 0 dog = auto() # 1
我用这些枚举作为NumPy数组的索引,同时需要一个能区分不同枚举类成员(即使其int值相同)的类字典对象,因为有时会在同一代码中处理不同类的键。但普通字典无法实现:
description_dict = { Fruit.apple: 'A round fruit with a thin peel', Fruit.pear: 'An oval fruit with a thin peel', Fruit.banana: 'An oblong fruit with a thick peel', Fruit.orange: 'A round fruit with a thick peel', Animal.cat: 'A pet that can accept you under certain circumstances', Animal.dog: 'A pet that always loves you', }
实际结果不符合预期:
>>> for key, val in description_dict.items(): ... print("{}: {}".format(repr(key), repr(val))) ... <Fruit.apple: 0>: 'A pet that can accept you under certain circumstances' <Fruit.pear: 1>: 'A pet that always loves you' <Fruit.banana: 2>: 'An oblong fruit with a thick peel' <Fruit.orange: 3>: 'A round fruit with a thick peel'
内容的提问来源于stack exchange,提问作者HelloGoodbye
相关产品推荐
相关产品推荐

