Home > Backend Development > Python Tutorial > How Can I Find a Dictionary Key Based on its Value in Python?

How Can I Find a Dictionary Key Based on its Value in Python?

Linda Hamilton
Release: 2024-12-23 18:12:15
Original
354 people have browsed it

How Can I Find a Dictionary Key Based on its Value in Python?

Retrieving Dictionary Keys Based on Value

When dealing with dictionaries in Python, it is often necessary to locate the key associated with a given value. This scenario arises when you need to find the name of a person based on their age, as in the following example:

dictionary = {'george': 16, 'amber': 19}
search_age = input("Provide age: ")  # Replace raw_input with input in Python 3
Copy after login

However, the provided code encounters a KeyError because it attempts to directly access the value without first verifying its existence. To rectify this, we employ a more robust approach using the following steps:

  1. Separate the Dictionary's Values: We create a list containing all the values from the dictionary: values_list = list(dictionary.values())
  2. Find the Value's Position: We determine the position of the searched value in the values_list using value_index = values_list.index(search_age)
  3. Retrieve the Matching Key: Using the value's position, we obtain the corresponding key from the dictionary's keys: name = list(dictionary.keys())[value_index]
  4. Print the Result: We display the retrieved name: print(name)

Consequently, our code now executes successfully:

mydict = {'george': 16, 'amber': 19}
search_age = input("Provide age: ")
values_list = list(mydict.values())
if search_age in values_list:
    value_index = values_list.index(search_age)
    name = list(mydict.keys())[value_index]
    print(name)
else:
    print("Age not found.")
Copy after login

The above is the detailed content of How Can I Find a Dictionary Key Based on its Value in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template