>>> d = {"foo": 12, "bar": 2, "jim": 4, "bob": 17} >>> [k for k, v in d.items() if v > 6]
I would just like to update this answer to also demonstrate the @glarrain solution, which I consider it my duty to use.
[k for k in d if d[k] > 6]
This is fully cross-compatible and does not require a vague change from .iteritems ( .iteritems avoids storing the list in memory in Python 2, which is fixed in Python 3), to .items .
@ Prof. Falken mentioned a solution to this problem
from six import iteritems
which effectively fixes BUT cross-compatibility issues requires you to download the six package
However, I do not completely agree with @glarrain that this solution is more readable, this is a discussion and, perhaps, only a personal preference, although Python should have only one way to do this. In my opinion, this depends on the situation (for example, you may have a long dictionary name that you do not want to enter twice, or you want the values ββto become a more readable name or some other reason).
Some interesting timings:
In Python 2, the second solution is faster; in Python 3, they are almost exactly equal in speed.
$ python -m timeit -s 'd = {"foo": 12, "bar": 2, "jim": 4, "bob": 17};' '[k for k, v in d.items() if v > 6]' 1000000 loops, best of 3: 0.772 usec per loop $ python -m timeit -s 'd = {"foo": 12, "bar": 2, "jim": 4, "bob": 17};' '[k for k, v in d.iteritems() if v > 6]' 1000000 loops, best of 3: 0.508 usec per loop $ python -m timeit -s 'd = {"foo": 12, "bar": 2, "jim": 4, "bob": 17};' '[k for k in d if d[k] > 6]' 1000000 loops, best of 3: 0.45 usec per loop $ python3 -m timeit -s 'd = {"foo": 12, "bar": 2, "jim": 4, "bob": 17};' '[k for k, v in d.items() if v > 6]' 1000000 loops, best of 3: 1.02 usec per loop $ python3 -m timeit -s 'd = {"foo": 12, "bar": 2, "jim": 4, "bob": 17};' '[k for k in d if d[k] > 6]' 1000000 loops, best of 3: 1.02 usec per loop
However, these are only tests for small dictionaries, in huge dictionary words, I am sure that without searching for the dictionary key ( d[k] ), I would make .items much faster. And it looks like this.
$ python -m timeit -s 'd = {i: i for i in range(-10000000, 10000000)};' -n 1 '[k for k in d if d[k] > 6]' 1 loops, best of 3: 1.75 sec per loop $ python -m timeit -s 'd = {i: i for i in range(-10000000, 10000000)};' -n 1 '[k for k, v in d.iteritems() if v > 6]' 1 loops, best of 3: 1.71 sec per loop $ python3 -m timeit -s 'd = {i: i for i in range(-10000000, 10000000)};' -n 1 '[k for k in d if d[k] > 6]' 1 loops, best of 3: 3.08 sec per loop $ python3 -m timeit -s 'd = {i: i for i in range(-10000000, 10000000)};' -n 1 '[k for k, v in d.items() if v > 6]' 1 loops, best of 3: 2.47 sec per loop