Open In App

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’]} 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 : 

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

 Method 2: Using dict comprehension + loop




# Python3 code to demonstrate working of
# Assign values to initialized dictionary keys
 
# Python3 code to demonstrate working of
# Values Associated Keys
# Using dict comprehension + loop
 
# 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 dict comprehension + loop
result_dict = {}
for key, val in test_dict.items():
    for ele in val:
        if ele in result_dict:
            result_dict[ele].append(key)
        else:
            result_dict[ele] = [key]
 
# printing result
print("The values associated dictionary : " + str(result_dict))

Output
The original dictionary is : {'gfg': [1, 2, 3], 'is': [1, 4], 'best': [4, 2]}
The values associated dictionary : {1: ['gfg', 'is'], 2: ['gfg', 'best'], 3: ['gfg'], 4: ['is', 'best']}

Time complexity: O(n^2), where n is the total number of values in all the lists in the test_dict. This is because we need to loop through all the values for each key in test_dict.

Auxiliary space: O(n), where n is the total number of values in all the lists in the test_dict. This is because we need to store the mapping from each value to its associated keys in the result_dict.

Method 3 : Using the setdefault() method of dictionary. 

Initialize an empty dictionary, result_dict, to store the values associated with keys.
Loop through the keys and values of the input dictionary, test_dict.
For each value, loop through its elements.
Use the setdefault() method to insert the element as a key in the result_dict if it is not already present, and assign an empty list as its value.
Append the key to the list of the element in the result_dict.
Print the result_dict.




# Python3 code to demonstrate working of
# Values Associated Keys
# Using setdefault()
 
# 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 setdefault()
result_dict = {}
for key, val in test_dict.items():
    for ele in val:
        result_dict.setdefault(ele, []).append(key)
 
# printing result
print("The values associated dictionary : " + str(result_dict))

Output
The original dictionary is : {'gfg': [1, 2, 3], 'is': [1, 4], 'best': [4, 2]}
The values associated dictionary : {1: ['gfg', 'is'], 2: ['gfg', 'best'], 3: ['gfg'], 4: ['is', 'best']}

The time complexity of this approach is O(n * m), where n is the number of keys in the input dictionary and m is the average number of elements in the values.
The auxiliary space of this approach is O(n * m), where n is the number of unique elements in the values and m is the average number of keys associated with each element.
 


Article Tags :