Python – Keys associated with value list in dictionary

Sometimes, while working with Python dictionaries, we can have a problem in which we need to find the key of particular value in value list. This problem in quite common and can have application in many domains. Lets discuss certain ways in which this task can be performed.

Method #1 : Using loop + items()
The combination of above functions can be used to solve this problem. In this, we extract all elements of dictionary using items() and loop is used to compile rest of logic.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Value's Key association
# Using loop + items()
  
# initializing dictionary
test_dict = {'gfg' : [4, 5], 'is' : [8], 'best' : [10, 12]}
  
# printing original dictionary
print("The original dictionary : " + str(test_dict))
  
# initializing value list 
val_list = [5, 10]
  
# Value's Key association
# Using loop + items()
temp = {}
for key, vals in test_dict.items():
    for val in vals:
        temp[val] = key
res = [temp[ele] for ele in val_list]
  
# printing result 
print("The keys mapped to " + str(val_list) + " are : " + str(res)) 

chevron_right


Output:

The original dictionary : {'gfg': [4, 5], 'best': [10, 12], 'is': [8]}
The keys mapped to [5, 10] are : ['gfg', 'best']

 

Method #2 : Using list comprehension + any()
This is yet another way in which this task can be performed. It offers shorthands that can be used to solve this problem. In this, we use any() to compute if key contains any of the values in value list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Value's Key association
# Using list comprehension + any()
  
# initializing dictionary
test_dict = {'gfg' : [4, 5], 'is' : [8], 'best' : [10, 12]}
  
# printing original dictionary
print("The original dictionary : " + str(test_dict))
  
# initializing value list 
val_list = [5, 10]
  
# Value's Key association
# Using list comprehension + any()
res = [key for key, val in test_dict.items() if any(y in val for y in val_list)]
  
# printing result 
print("The keys mapped to " + str(val_list) + " are : " + str(res)) 

chevron_right


Output:

The original dictionary : {'gfg': [4, 5], 'is': [8], 'best': [10, 12]}
The keys mapped to [5, 10] are : ['gfg', 'best']



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.