Open In App

Inverse Dictionary Values List – Python

Last Updated : 28 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a dictionary and the task is to create a new dictionary where each element of the value lists becomes a key and the original keys are grouped as lists of values for these new keys.
For example: dict = {1: [2, 3], 2: [3], 3: [1]} then output will be {2: [1], 3: [1, 2], 1: [3]}

Using defaultdict

In this method we use defaultdict from the collections module to efficiently reverse the key-value mapping in a dictionary. It iterates through each key-value pair thus appending the key to the corresponding list in the result.

Python
from collections import defaultdict

d = {1: [2, 3], 2: [3], 3: [1], 4: [2, 1]}

# Reverse mapping
res = defaultdict(list)
for k, v in d.items():
    for i in v:
        res[i].append(k)

print(dict(res))

Output
{2: [1, 4], 3: [1, 2], 1: [3, 4]}

Using setdefault()

This method uses the setdefault() method from the dictionary to initialize the list for each key that doesn’t exist in the result dictionary. It iterates through the original dictionary and appends the key to the list of each value.

Python
d = {1: [2, 3], 2: [3], 3: [1], 4: [2, 1]}

# Reverse mapping
res = {}
for k, v in d.items():
    for i in v:
        res.setdefault(i, []).append(k)

print(res)

Output
{2: [1, 4], 3: [1, 2], 1: [3, 4]}

Explanation: Outer loop processes each key-value pair and the setdefault() method ensures that each key in the result dictionary has a list initialized before appending the key to it.



Next Article

Similar Reads