How to Get Key by Value in Dictionary in Python

Created
Modified

Using keys Function

Basically, it separates the dictionary's values in a list, finds the position of the value you have, and gets the key at that position.

The following example:

#!/usr/bin/python3

d = {"a": 1, "b": 2, "c": 1}
key = list(d.keys())[list(d.values()).index(1)]
print(key)
a

Using List Comprehension

Using a list comprehension is the most Pythonic way:

#!/usr/bin/python3

d = {"a": 1, "b": 2, "c": 1}
keys = [key for key, val in d.items() if val == 1]
print(keys)
['a', 'c']

Using dict Method

The following example should cover whatever you are trying to do:

#!/usr/bin/python3

d = {"a": 1, "b": 2, "c": 1}
key = dict((v,k) for k,v in d.items()).get(1)
print(key)
c

Related Tags