我创建了一个类,它允许我使用任意字典键存储元数据,并且仍然通过原始对象类型的 in
测试:
class DictKey:
def __init__(self, key):
self.hashkey = hash(key)
self.member = key
def __hash__(self):
return self.hashkey
def __repr__(self):
return 'DictKey(' + self.strkey + ')'
def __cmp__(self, o):
return cmp(self.member, o)
d = {}
key = DictKey('hello')
d[key] = 'world'
print key.hashkey
print hash('hello')
print key in d
print 'hello' in d
print DictKey('hello') in d
产生输出:
840651671246116861
840651671246116861
True
True
True
现在,给定字符串“hello”,我需要获取在恒定时间内从所述字符串创建的 DictKey 实例:
if 'hello' in d:
#need some way to return the instance of DictKey so I can get at it's member
tmp = d.getkey('hello')
tmp.member
最佳答案
将“元”数据与字典一起存储的更传统方法是:
- 使用相同的一组键维护两个
dict
,一个用于实际数据,一个用于“元” - 拥有一个带有(“原始”)键的
dict
,值是 2 元组:( value, item-meta-data )
两者都很简单,不需要特殊的魔法。您还可以避免像您在问题中描述的问题(以及即将出现的其他问题)之类的问题。
关于collections - python 从字典中检索关键对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15693605/