Get key from value in Dictionary in Python

PythonServer Side ProgrammingProgramming

Python dictionary contains key value pairs. In this article we aim to get the value of the key when we know the value of the element. Ideally the values extracted from the key but here we are doing the reverse.

With index and values

We use the index and values functions of dictionary collection to achieve this. We design a list to first get the values and then the keys from it.

Example

 Live Demo

dictA = {"Mon": 3, "Tue": 11, "Wed": 8}
# list of keys and values
keys = list(dictA.keys())
vals = list(dictA.values())
print(keys[vals.index(11)])
print(keys[vals.index(8)])
# in one-line
print(list(dictA.keys())[list(dictA.values()).index(3)])

Output

Running the above code gives us the following result −

Tue
Wed
Mon

With items

We design a function to take the value as input and compare it with the value present in each item of the dictionary. If the value matches the key is returned.

Example

 Live Demo

dictA = {"Mon": 3, "Tue": 11, "Wed": 8}
def GetKey(val):
   for key, value in dictA.items():
      if val == value:
         return key
      return "key doesn't exist"
print(GetKey(11))
print(GetKey(3))
print(GetKey(10))

Output

Running the above code gives us the following result −

Tue
Mon
key doesn't exist
raja
Published on 04-Jun-2020 12:18:42
Advertisements