collections - python 从字典中检索关键对象

标签 collections python-2.7

我创建了一个类,它允许我使用任意字典键存储元数据,并且仍然通过原始对象类型的 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

最佳答案

将“元”数据与字典一起存储的更传统方法是:

  1. 使用相同的一组键维护两个dict,一个用于实际数据,一个用于“元”
  2. 拥有一个带有(“原始”)键的 dict,值是 2 元组:( value, item-meta-data )

两者都很简单,不需要特殊的魔法。您还可以避免像您在问题中描述的问题(以及即将出现的其他问题)之类的问题。

关于collections - python 从字典中检索关键对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15693605/

相关文章:

java - Collections.sort 排序错误列表

collections - Java 中保存最后 N 个元素的大小受限队列

java - 没有任何内容的对象/空对象

Python 3.5 "ImportError: cannot import name ' 某个名字'

python - 交互模式与非交互模式下相同代码中的不同导入行为 - 为什么模块搜索路径不同?

python - chrome_options.binary_location() TypeError : 'str' object is not callable

ruby-on-rails - Ruby on Rails - 部分使用集合循环时出现问题

java - 空安全集合包含方法

python - JSON对象无法解码

python - 如何在列表框上绑定(bind) "select all"事件?