重点对象我创建了一个类,让我来存储元数据与任意词典按键,仍然与原来的对象类型通过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
现在,给出的字符串“你好”,我需要一个从所述串是在固定时间内创建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
我试图避免使用双字典解决方案,因为不必使用该空间就很好(我们应用程序中的字典可能会变得非常大)。但是,看起来这将是一条路。谢谢! – Hersheezy
@Hersheezy如果你觉得这个答案有帮助,可以随时接受它;) – shx2