Python dictionary get key | Example code

There are many ways to get a key form dictionary like using the index() method, item() method or iterate over keys in python.

The simplest way is using the keys() method to get the object view list of keys from the dictionary.


If you want to access both the key and value, use the following:

for key, value in my_dict.items():
    print(key, value)

Python dictionary get key Example

Simple example code.

Using keys() method

This method returns a view object that displays a list of all the keys in the dictionary in order of insertion.

dict1 = {"A": 2, "B": 3, "C": 4}



Python dictionary get key

Using list.index()

Use index() method to fetch Dictionary key using value.

dict1 = {"A": 2, "B": 3, "C": 4}

# GET list out keys and values
key_list = list(dict1.keys())
val_list = list(dict1.values())

# print key of value 2
position = val_list.index(2)

Output: A

Using dict.item() 

Get key from a value by matching all the values and then print the corresponding key to the given value.

dict1 = {"A": 2, "B": 3, "C": 4}

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


Output: B

Through iteration get all keys from dictionary

dict1 = {"A": 2, "B": 3, "C": 4}

for key, value in dict1.items():



Do comment if you have any doubts and suggestions on this Python dictionary tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.