There are many ways to get a key form dictionary like using the index() method, item() method, or iterating over keys in python.
The simplest way is using the keys() method to get the object view list of keys from the dictionary.
dict.keys()
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}
print(dict1.keys())
Output:
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)
print(key_list[position])
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
print(get_key(3))
Output: B
Through iteration get all keys from dictionary
dict1 = {"A": 2, "B": 3, "C": 4}
for key, value in dict1.items():
print(key)
Output:
A
B
C
Do comment if you have any doubts or suggestions on this Python dictionary tutorial.
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.