Python – Keys associated with Values in Dictionary
Sometimes, while working with Python dictionaries, we can have problem in which we need to reform the dictionary, in the form in which all the values point to the keys that they belong to. This kind of problem can occur in many domains including web development and data domains. Lets discuss certain way in which this task can be performed.
Input : test_dict = {‘abc’ : [10, 30], ‘bcd’ : [30, 40, 10]}
Output : {10: [‘abc’, ‘bcd’], 30: [‘abc’, ‘bcd’], 40: [‘bcd’]}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
Input : test_dict = {‘gfg’ : [1, 2, 3], ‘is’ : [1, 4], ‘best’ : [4, 2]}
Output : {1: [‘is’, ‘gfg’], 2: [‘gfg’, ‘best’], 3: [‘gfg’], 4: [‘is’, ‘best’]}
Method : Using defaultdict() + loop
The combination of above functionalities can solve this problem. In this, we create defaultdict of list and insert the element by checking the association inside the look using brute force approach.
# Python3 code to demonstrate working of # Values Associated Keys# Using defaultdict() + loopfrom collections import defaultdict # initializing dictionarytest_dict = {'gfg' : [1, 2, 3], 'is' : [1, 4], 'best' : [4, 2]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Values Associated Keys# Using defaultdict() + loopres = defaultdict(list)for key, val in test_dict.items(): for ele in val: res[ele].append(key) # printing result print("The values associated dictionary : " + str(dict(res))) |
The original dictionary is : {'is': [1, 4], 'gfg': [1, 2, 3], 'best': [4, 2]}
The values associated dictionary : {1: ['is', 'gfg'], 2: ['gfg', 'best'], 3: ['gfg'], 4: ['is', 'best']}

