Python – Inverse Dictionary Values List
Last Updated :
10 Mar, 2023
Given a Dictionary as value lists, inverse it, i.e map elements in list to keys and create new values list.
Input : test_dict = {1: [2, 3], 2: [3], 3: [1]} Output : {2: [1], 3: [1, 2], 1: [3]} Explanation : List elements mapped with their keys. Input : test_dict = {1: [2, 3, 4]} Output : {2: [1], 3: [1], 4: [1]} Explanation : List elements mapped with their keys.
Method : Using defaultdict() + loop
This is a way in which this task can be performed. In this, we initialize result keys with dictionary list, and iterate using loop to assign each value its keys, and reform the result dictionary values list.
Python3
from collections import defaultdict
test_dict = { 1 : [ 2 , 3 ], 2 : [ 3 ], 3 : [ 1 ], 4 : [ 2 , 1 ]}
print ( "The original dictionary is : " + str (test_dict))
res = defaultdict( list )
for keys, vals in test_dict.items():
for val in vals:
res[val].append(keys)
print ( "The required result : " + str ( dict (res)))
|
Output
The original dictionary is : {1: [2, 3], 2: [3], 3: [1], 4: [2, 1]}
The required result : {2: [1, 4], 3: [1, 2], 1: [3, 4]}
Time Complexity: O(n*n) where n is the number of elements in the dictionary
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the dictionary
Share your thoughts in the comments
Please Login to comment...