-1

What would be the most efficient way to get all dict items with value == 3 and create a new dict?

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?

David542
  • 104,438
  • 178
  • 489
  • 842

1 Answers1

5

You could use a dict comprehension:

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.


As you can see from the timeit.timeit tests below, this solution is more efficient:

>>> 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.

  • I get that this is simpler, but is it more efficient? – taesu Jan 25 '15 at 21:19
  • 2
    If the OP needs to do this for multiple values he may want to make an inverse mapping: `d_inverse = {};for k, v in d.items():d2.setdefault(v, []).append(k)`. This would be slower for one value, but likely faster for multiple values. – Steven Rumbalski Jan 25 '15 at 21:40