按值构建查找键的字典

时间:2012-09-21 09:22:30

标签: python

字典通常很适合按键查找值,但按值查找键非常慢

for k,v in dictionary.items():
    if v = myValue:
        return k

是否已有一个数据结构同时生成key-> value和ke

3 个答案:

答案 0 :(得分:8)

您可以尝试bidict

>>> husbands2wives = bidict({'john': 'jackie'})
>>> husbands2wives['john'] # the forward mapping is just like with dict
'jackie'
>>> husbands2wives[:'jackie'] # use slice for the inverse mapping
'john'

答案 1 :(得分:5)

只需创建倒置映射:

from collections import defaultdict
inverted = defaultdict(list)
for k, v in dictionary.iteritems():
    inverted[v].append(k)

请注意,上面的代码处理重复值; inverted[v]会返回包含该值的列表

如果您的值也是唯一的,则可以使用简单的字典而不是defaultdict

inverted = { v: k for k, v in dictionary.iteritems() }

或者,在python 3中,items()是字典视图:

inverted = { v: k for k, v in dictionary.items() }

答案 2 :(得分:0)

Python 3:

revdict = {v:k for k,v in dictionary.items()}

(Python 2使用.iteritems()代替)