已经回答了,但是由于有几个人提到反转字典,因此这是您在一行中进行操作的方式(假设1:1映射)和一些各种性能数据:
python 2.6:
reversedict = dict([(value, key) for key, value in mydict.iteritems()])
2.7+:
reversedict = {value:key for key, value in mydict.iteritems()}
如果您认为不是1:1,则仍然可以用几行代码创建合理的反向映射:
reversedict = defaultdict(list)
[reversedict[value].append(key) for key, value in mydict.iteritems()]
速度有多慢:比简单的搜索要慢,但是却没有您想像的慢-在“直” 100000条目字典上,“快速”搜索(即在键中寻找一个早的值)比反转整个字典快约10倍,“慢速”搜索(快到结尾)约快4-5倍。因此,经过最多约10次查询后,它是自付费用的。
第二个版本(每个项目都有列表)的花费约为简单版本的2.5倍。
largedict = dict((x,x) for x in range(100000))
# Should be slow, has to search 90000 entries before it finds it
In [26]: %timeit largedict.keys()[largedict.values().index(90000)]
100 loops, best of 3: 4.81 ms per loop
# Should be fast, has to only search 9 entries to find it.
In [27]: %timeit largedict.keys()[largedict.values().index(9)]
100 loops, best of 3: 2.94 ms per loop
# How about using iterkeys() instead of keys()?
# These are faster, because you don't have to create the entire keys array.
# You DO have to create the entire values array - more on that later.
In [31]: %timeit islice(largedict.iterkeys(), largedict.values().index(90000))
100 loops, best of 3: 3.38 ms per loop
In [32]: %timeit islice(largedict.iterkeys(), largedict.values().index(9))
1000 loops, best of 3: 1.48 ms per loop
In [24]: %timeit reversedict = dict([(value, key) for key, value in largedict.iteritems()])
10 loops, best of 3: 22.9 ms per loop
In [23]: %%timeit
....: reversedict = defaultdict(list)
....: [reversedict[value].append(key) for key, value in largedict.iteritems()]
....:
10 loops, best of 3: 53.6 ms per loop
使用ifilter也有一些有趣的结果。从理论上讲,ifilter应该更快,因为我们可以使用itervalues(),而不必创建/遍历整个值列表。实际上,结果是...很奇怪...
In [72]: %%timeit
....: myf = ifilter(lambda x: x[1] == 90000, largedict.iteritems())
....: myf.next()[0]
....:
100 loops, best of 3: 15.1 ms per loop
In [73]: %%timeit
....: myf = ifilter(lambda x: x[1] == 9, largedict.iteritems())
....: myf.next()[0]
....:
100000 loops, best of 3: 2.36 us per loop
因此,对于较小的偏移量,它比以前的任何版本都快得多(2.36 * u * S,而以前的版本最低为1.48 * m * S)。但是,对于列表末尾附近的较大偏移量,它的速度要慢得多(15.1ms与相同的1.48mS)。恕我直言,低端的少量节省不值得高端的成本。