[toc]
Problem Statement: How to get a key by its value in a dictionary in Python
β₯οΈ Info: Are you AI curious but you still have to create real impactful projects? Join our official AI builder club on Skool (only $5): SHIP! - One Project Per Month
Example:
# Given dictionary
employee = {"Sam": 1010, "Bob": 2020, "Rob": 3030}
# Some Way to extract the Key 'Bob' using its value 2020We have a clear idea about the problem now. So without further delay, let us dive into the solutions to our question.
π¬Video Walkthrough
Solution 1: Using dict.items()
Approach: One way to solve our problem and extract the key from a dictionary by its value is to use the dict.items(). The idea here is to create a function that takes the provided value as an input and compares it to all the values present in the dictionary. When we get the matching value, we simply return the key assigned to the value.
Solution:
# Given dictionary
employee = {"Sam": 1010, "Bob": 2020, "Rob": 3030}
# Function that fetches key from value
def get_key(v):
for key, value in employee.items():
# return the key which matches the given value
if v == value:
return key
return "The provided key is not present in the dictionary"
# Passing the keys to the function
print("Employee ID - 2020 \nName - ", get_key(2020))Output:
Employee ID - 2020
Name - BobNote: dict.items() is a dictionary method in Python that returns a view object. The returned view object contains a list of tuples that comprises the key-value pairs in the dictionary. Any changes made to the dictionary will also be reflected in the view object.
Example: The following example demonstrates how the dict.items() method works.
# Given dictionary
employee = {"Sam": 1010, "Bob": 2020, "Rob": 3030}
item = employee.items()
employee['Tom'] = '4040'
print(item)Output:
dict_items([('Sam', 1010), ('Bob', 2020), ('Rob', 3030), ('Tom', '4040')])Solution 2: Using keys(), values() and index()
Approach: Another workaround to solve our problem is to extract the keys and values of the dictionary separately in two different lists with the help of the keys() and values() methods. Then find the index/position of the given value from the list that stores the values with the help of the index() method. Once the index is found, you can easily locate the key corresponding to this index from the list that stores all the keys.
Solution: Please follow the comments within the code to get an insight of the solution.
# Given dictionary
employee = {"Sam": 1010, "Bob": 2020, "Rob": 3030}
# store all the keys in a list
key = list(employee.keys())
# store all the values in another list
val = list(employee.values())
# find the index of the given value (2020 in this case)
loc = val.index(2020)
# Use the index to locate the key
print(key[loc])Output:
Bob
Note:
keys()is a dictionary method that returns a view object that contains the keys of the dictionary in a list.values()is a dictionary method that returns a view object consisting of the values in the dictionary within a list.- The
index()method is used to return the index of the specified item in a list. The method returns only the first occurrence of the matching item.
Example:
employee = {"Sam": 1010, "Bob": 2020, "Rob": 3030}
li = ['Lion', 'Dog', 'Cat', 'Mouse', 'Dog']
key = list(employee.keys())
val = list(employee.values())
loc = li.index('Dog')
print(f"Keys: {key}")
print(f"Values: {val}")
print(f"Index: {loc}")Output:
Keys: ['Sam', 'Bob', 'Rob'] Values: [1010, 2020, 3030] Index: 1
Solution 3: Interchanging the Keys and Values
Approach: The given problem can be resolved using a single line of code. The idea is to use a dictionary comprehension that reverses the keys and values. This means the keys in the original dictionary become the values in the newly created dictionary while the values in the original dictionary become the keys in the newly created dictionary. Once you have interchanged the keys and values, you can simply extract the key by its value.va
Solution:
employee = {"Sam": 1010, "Bob": 2020, "Rob": 3030}
res = dict((val, key) for key, val in employee.items())
print("Original Dictionary: ", employee)
print("Modified Dictionary: ", res)
# using res dictionary to find out the required key from employee dictionary
print(res[2020])Output:
Original Dictionary: {'Sam': 1010, 'Bob': 2020, 'Rob': 3030}
Modified Dictionary: {1010: 'Sam', 2020: 'Bob', 3030: 'Rob'}
BobExplanation:
employeedictionary has Name and Employee ID as Key-Value pairs.resdictionary interchanges the keys and values of theemployeedictionary. Therefore,resnow has Employee ID and Name as Key-Value pairs.- Since we need to extract the name corresponding to an Employee ID. We can simply get that from the
resdictionary with the help of the key which in this case is the Employee ID.
Solution 4: Using zip()
Considering that the values in the given dictionary are unique, you can solve the problem with a single line of code. The idea is to use the keys() and values() dictionary methods to extract the keys and values from the dictionary and then tie them together with the help of the zip() method to produce a dictionary.
employee = {"Sam": 1010, "Bob": 2020, "Rob": 3030}
name = dict(zip(employee.values(), employee.keys()))[2020]
print(f'Name: {name} \nEmployee ID: 2020')Output:
Name: Bob Employee ID: 2020
Solution 5: Using Pandas
We can also opt to use the Pandas DataFrame to get the key by its value. In this approach, first, we will convert the given dictionary into a data frame. Further, we can name the column with the keys as “key” and the columns with the values as “value“. To get the key by the given value, we have to return the value from the ‘key‘ column from the row where the value of the ‘value‘ column is the required value.
Example:
# Importing the pandas module
import pandas as pd
# Given dictionary
employee = {"Sam": 1010, "Bob": 2020, "Rob": 3030}
# list to store the keys from the dictionary
key = list(employee.keys())
# list to store the values from the dictionary
val = list(employee.values())
# Converting the dictionary into a dataframe
df = pd.DataFrame({'key': key, 'value': val})
print("The data frame:")
print(df)
# Given Value
v = 2020
print("The given value is", v)
# Searching for the key by the given value
k = (df.key[df.value == v].unique()[0])
print("The key associated with the given value is:", k)Output:
The data frame: key value 0 Sam 1010 1 Bob 2020 2 Rob 3030 The given value is 2020 The key associated with the given value is: Bob
Note: df.key[df.value == v].unique()[0]) –> We have to use the unique method in this line to avoid the index from getting printed. While using the panda’s data frame, the output is not in the string format, but it is a pandas series object type. Hence, we need to convert it using the unique or sum() method. Without the unique method, the output will also consider the index of the data frame column.
Conclusion
That’s all about how to get a key by the value in the dictionary. I hope you found it helpful. Please stay tuned and subscribe for more interesting tutorials. Happy Learning!