简体   繁体   English

逆字典映射的性能

[英]Performance of inverse dictionary mapping

What would be the most efficient way to get all dict items with value == 3 and create a new dict? 获取value == 3所有字典项并创建新字典的最有效方法是什么?

Here is what I have thus far: 到目前为止,这是我所拥有的:

d = {1: 2, 2: 2, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, ...}
new_d = {}
for item in d:
    if d[item] == 3:
        new_d[item] = d[item]

Is there a more efficient, simpler way to do this? 有没有更有效,更简单的方法来做到这一点? Perhaps using a map? 也许使用地图?

You could use a dict comprehension : 您可以使用dict理解

new_d = {k:v for k, v in d.items() if v == 3}

Note that you should call d.iteritems() in Python 2.x to avoid creating an unnecessary list. 请注意,您应该在Python 2.x中调用d.iteritems()以避免创建不必要的列表。


As you can see from the timeit.timeit tests below, this solution is more efficient: 从下面的timeit.timeit测试可以看出,该解决方案效率更高:

>>> from timeit import timeit
>>> d = {1: 2, 2: 2, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1}
>>>
>>> timeit('''
... new_d = {}
... for item in d:
...     if d[item] == 1:
...          new_d[item] = d[item]
... ''', 'from __main__ import d')
5.002458692375711
>>>
>>> timeit('new_d = {k:v for k, v in d.items() if v == 1}', 'from __main__ import d')
4.844044424640543
>>>

It is also a lot simpler, which is always good. 它也简单得多,总是很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM