![]() |
|
[Tut] Get Key by Value in The Dictionary - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Get Key by Value in The Dictionary (/thread-99244.html) |
[Tut] Get Key by Value in The Dictionary - xSicKxBot - 04-19-2022 Get Key by Value in The Dictionary Table of Contents
Problem Statement: How to get a key by its value in a dictionary in Python Example: Code: # 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. [b]Solution 1: Using dict.items()[/b] Approach: One way to solve our problem and extract the key from a dictionary by its value is to use the Code: dict.items()Solution: Code: # 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: Code: Employee ID - 2020 Name - BobNote: Code: dict.items()Example: The following example demonstrates how the Code: dict.items()Code: # Given dictionary
employee = {"Sam": 1010, "Bob": 2020, "Rob": 3030}
item = employee.items()
employee['Tom'] = '4040'
print(item)Output: Code: dict_items([('Sam', 1010), ('Bob', 2020), ('Rob', 3030), ('Tom', '4040')])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 Code: keys()Code: values()Code: index()Solution: Please follow the comments within the code to get an insight of the solution. Code: # 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: Code: BobNote:
Example: Code: 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: Code: Keys: ['Sam', 'Bob', 'Rob']
Values: [1010, 2020, 3030]
Index: 1Approach: 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: Code: 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: Code: Original Dictionary: {'Sam': 1010, 'Bob': 2020, 'Rob': 3030}
Modified Dictionary: {1010: 'Sam', 2020: 'Bob', 3030: 'Rob'}
BobExplanation:
[b]Solution 4: Using zip()[/b] 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 Code: keys()Code: values()Code: zip()Code: employee = {"Sam": 1010, "Bob": 2020, "Rob": 3030}
name = dict(zip(employee.values(), employee.keys()))[2020]
print(f'Name: {name} \nEmployee ID: 2020')Output: Code: Name: Bob Employee ID: 2020We 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 “ Code: keyCode: valueCode: keyCode: valueExample: Code: # 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: Code: 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: BobNote: Code: df.key[df.value == v].unique()[0])[b]Conclusion[/b] 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! |