Skip to content
Related Articles

Related Articles

Improve Article

Python – Keys associated with value list in dictionary

  • Last Updated : 08 May, 2020

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.




# 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)) 
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.






# 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)) 
Output:
The original dictionary : {'gfg': [4, 5], 'is': [8], 'best': [10, 12]}
The keys mapped to [5, 10] are : ['gfg', 'best']

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :