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.

nput : test_dict = {‘abc’ : [10, 30], ‘bcd’ : [30, 40, 10]}
Output : {10: [‘abc’, ‘bcd’], 30: [‘abc’, ‘bcd’], 40: [‘bcd’]}

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() + loop
from collections import defaultdict

# initializing dictionary
test_dict = {'gfg' : [1, 2, 3], 'is' : [1, 4], 'best' : [4, 2]}

# printing original dictionary
print("The original dictionary is : " + str(test_dict))

# Values Associated Keys
# Using defaultdict() + loop
res = 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)))

Output :

he 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']}