Skip to content

Python dictionary get key from the value | Example code

  • by

Use the items() method with for loop to get key from the value in Python dictionary. Fetch key from a value by matching all the values and then print the corresponding key to the given value.

Example dictionary gets key from the value in Python

Simple example code function to return key for any value. This is a custom function.

def get_key(val):
    for key, value in my_dict.items():
        if val == value:
            return key

    return "key doesn't exist"

# Driver Code

my_dict = {"Java": 100, "Python": 200, "C": 300}



Python dictionary get key from the value

Or you can write a list comprehension to pull out the matching keys.

my_dict = {"Java": 100, "Python": 200, "C": 300}

res = ([k for k,v in my_dict.items() if v == 200])

How to get the key of a particular value in dictionary python using an index?

Answer: Separates the dictionary’s values in a list, finds the position of the value you have, and gets the key at that position.

my_dict = {"Java": 100, "Python": 200, "C": 300}

res = list(my_dict.keys())[list(my_dict.values()).index(100)]


Output: Java

Do comment if you have any doubts or suggestions on this Python dictionary topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading