Skip to content

Python dict getkey | Example code

  • by

You can use list.index() method or dict.item() method to Get key from a value in Python Dictionary.

Example dict getkey in Python

Simple example code created a function “getkey” to return key for any value from dict.

Using dict.item()

Fetch key from a value.

def getkey(val, dict1):
    for key, value in dict1.items():
        if val == value:
            return key

    return "key doesn't exist"


my_dict = {"A": 1, "B": 2, "C": 3}

print(getkey(1, my_dict))

Output:

Python dict getkey

Using list.index()

In this method, you have to convert the dictionary into a list of keys and values separately.

my_dict = {"A": 1, "B": 2, "C": 3}


def get_key(value, dict1):
    key_list = list(dict1.keys())
    val_list = list(dict1.values())

    position = val_list.index(value)
    
    return key_list[position]


print(get_key(1, my_dict))

Output: A

The one-liner approach get key from dict

my_dict = {"A": 1, "B": 2, "C": 3}

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

print(res)

Output: C

Do comment if you have any doubts and suggestions on this Python dict key 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