python

How to get key by value in dictionary in Python

In this tutorial, we are going to see how to find all the keys associated to a single value or to several values.

  • Using item() method
  • Using a comprehension list
 

How to get key by value in a dictionary using item() method

item() returns an iterable sequence of all key-value pairs in the dictionary. So we will go through this sequence and for each entry we will check if the value is identical to the given value, then we will add the key to a new list.

# function to return the key for any value
def find_key(v): 
    for k, val in color_dict.items(): 
        if v == val: 
            return k 

    return "Key does not exist"
  

color_dict ={"blue":1, "green":2, "red":3, "orange":4} 

print(find_key(1))  
print(find_key(2)) 
print(find_key(3))

Output:

blue
green
red
 

How to get key by value in a dictionary using a comprehension list

The same can be achieved with comprehension lists.

color_dict ={"blue":1, "green":2, "red":3, "orange":4} 
#get list of keys with value = 2 
key_list = [k  for (k, val) in color_dict.items() if val == 2]
#Print the key
print(key_list)

Output:

['green']
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *