+1 vote
in Programming Languages by (74.6k points)
I want to find all the keys in a Python dictionary that contain a certain value, such as 123. Is there a Pythonic way to do this?

1 Answer

+3 votes
by (13.2k points)
selected by
 
Best answer

The most Pythonic and efficient approach for this task is list comprehension with ".items()". You can also use filter and a lambda function.

Here is an example:

>>> aa={'a':123, 'b':323, 'c':123, 'd':123, 'e':453, 'f':56}

>>> aa

{'a': 123, 'b': 323, 'c': 123, 'd': 123, 'e': 453, 'f': 56}

>>> [k for k, v in aa.items() if v == 123]

['a', 'c', 'd']

Another approach:

>>> list(filter(lambda key: aa[key] == 123, aa))

['a', 'c', 'd'] 


...