Ways to get keys by value from a Python Dictionary

Python Dictionary

In this post, we are going to learn about the different ways to get keys by value from a Python Dictionary. The dictionary is an order collection of key-value pairs. The key in the dictionary is unique and used to get value based on the key. But in this post, we are going to get the key based on values, sometimes we have values and we want to access its key.

Let us start with our different ways to do this job.

1. For loop to get the key by value from a Python Dictionary

In this approach, we are using the ‘for’ loop to run over the dictionary items and compare each value of the dictionary with the values we want to find. If the values exist in the dictionary, we are then appending matching key values into the list. Here in the example dictionary, we have more than one key that has the same values paired with them. In this case, it returns multiples keys.

Code Example

#Program to Get a key by value from a Python Dictionary

sub_dict = {'math' : 100, 'chem' : 98, 'sci' : 100,'eng':100,'Music':100,'Drawing':100} 

def Find_keys_by_values(dict,val_to_find): 
   #listofvalues = dict.items()
   listofkeys = list()
   for key, value in dict.items(): 
      if value == val_to_find:
       listofkeys.append(key)
   print('key of given value\n =',listofkeys)

#calling the method 
Find_keys_by_values(sub_dict,100)

Output

key of given value
 = ['math', 'sci', 'eng', 'Music', 'Drawing']

2.Using list comprehension

The second approach to do the desired job is by using list comprehension. The above example code can be written in one line using list comprehension. We are going to do the same in the below code example. If multiple keys have the same value then it returns multiple keys.

Code Example

#Program to Get a key by value from a Python Dictionary
sub_dict = {'math' : 100, 'chem' : 98, 'sci' : 100,'eng':100,'Music':100,'Drawing':100} 

def Find_keys_by_values(dict,val_to_find): 
 mylist = list()
 mylist =[key  for (key, value) in sub_dict.items() if value == val_to_find]
   
 print('key of given value\n =',mylist)

#calling the method 
Find_keys_by_values(sub_dict,100)

Output

key of given value
 = ['math', 'sci', 'eng', 'Music', 'Drawing']

3.Get keys for a list of values

In this code example, we will understand how to get keys, if we have a list of values.We have a function name Find_keys_by_values(),It takes two parameters dictionary,list of values. We are looping over the dictionary items using the ‘for’ loop and check if the value exists in val_to_find_list. If it exists we are appending its key in the list and printing the list of keys.

Code Example

#Program to Get a key by value from a Python Dictionary

sub_dict = {'math' : 97, 'chem' : 98, 'sci' : 100,'eng':99,'Music':100,'Drawing':100} 
def Find_keys_by_values(dict,val_to_find_list):   
   listofkeys = list()
   for key, value in dict.items():
    if value in val_to_find_list:
       listofkeys.append(key)
   print('key of given value\n =',listofkeys)

#calling the method 
Find_keys_by_values(sub_dict,[98,97,99])

Output

key of given value
 = ['math', 'chem', 'eng']

4.Using Pandas DataFrame

In this example, we are using the Pandas library of Python. We are creating two columns one for all keys and one for all values and finally, we are looking for values that are equal to 100 (which is the value for which we are finding the key) and converting them into a list, and printing the keys.

Code Example

#Program to Get a key by value from a Python Dictionary

import pandas as pd
sub_dict = {'math' : 97, 'chem' : 98, 'sci' : 100,'eng':99,'Music':100,'Drawing':100} 
df = pd.DataFrame({'key':list(sub_dict.keys()),'val':list(sub_dict.values())})

list_of_keys = list(df.key[df.val==100])
print('list of keys by value =\n',list_of_keys)

Output

list of keys by value =
 ['sci', 'Music', 'Drawing']

5. Dictionary to list

In this code example, we are converting dictionary key-values into a key list and values into a value list. The next step is to Find the matching index from value_list and using that index to find the key from the key list. It only returns the first match key.

Code Example

#Program to Get a key by value from a Python Dictionary

sub_dict = {'math' : 97, 'chem' : 98, 'sci' : 100,'eng':99,'Music':100,'Drawing':100} 

def get_keys_byVal(dict,value):
 key = list(dict.keys())[list(dict.values()).index(value)]
   
 print('list of keys by value =\n',key)

get_keys_byVal(sub_dict,100)

Output

list of keys by value =
 sci

Conclusion

In this post, We tried to explain different ways to get keys by value from a Python Dictionary, Using these ways we can easily find keys and all the matching keys by values. We hope you find it useful and will apply in your programs.

Happy Learning!!