Collections python从字典中检索键对象
我创建了一个类,该类允许我使用任意字典键存储元数据,并且仍然使用原始对象类型通过Collections python从字典中检索键对象,collections,python-2.7,Collections,Python 2.7,我创建了一个类,该类允许我使用任意字典键存储元数据,并且仍然使用原始对象类型通过中的测试: class DictKey: def __init__(self, key): self.hashkey = hash(key) self.member = key def __hash__(self): return self.hashkey def __repr__(self): return 'DictKe
中的测试:
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
我对您的基本代码做了一点修改:
def __repr__(self):
return 'DictKey(' + self.member + ')'
然后,如果要检索密钥集中DictKey的实例,可以执行以下操作:
index_of_instance = d.keys().index('hello')
my_instance_of_dict_key = d.keys()[index_of_instance]
希望有帮助。与dict一起存储“元数据”的更传统的方法是:
用同一组键维护两个dict
s,一个用于实际数据,一个用于“meta”
使用带有(“原始”)键的dict
,值为2元组:(值,项元数据)
两者都很简单,不需要特殊的魔法。您还可以避免您在问题中描述的问题(以及其他问题)。我相信对keys()的两个调用都是O(n)。我需要的查找是恒定的时间。谢谢你!我试图避免使用双dict解决方案,因为不必使用该空间(我们应用程序中的字典可能会变得非常大)会很好。然而,看起来这将是一条路要走。谢谢@Hersheezy如果你觉得这个答案有帮助,请接受它;)