Python Keys associated with Values in Dictionary (original) (raw)

Last Updated : 6 Nov, 2025

Given a dictionary in Python, our task is to reverse the mapping, i.e., create a new dictionary where each value points to the keys it belongs to. This operation is useful in data organization, analytics, and web applications.

**Example:

Input: {'abc': [10, 30], 'bcd': [30, 40, 10]}
Output: {10: ['abc', 'bcd'], 30: ['abc', 'bcd'], 40: ['bcd']}

Using defaultdict() + Loop

defaultdict from the collections module simplifies grouping by automatically initializing missing keys.

Python `

from collections import defaultdict

d = {'gfg': [1, 2, 3], 'is': [1, 4], 'best': [4, 2]} res = defaultdict(list) for key, vals in d.items(): for v in vals: res[v].append(key) print(dict(res))

`

Output

{1: ['gfg', 'is'], 2: ['gfg', 'best'], 3: ['gfg'], 4: ['is', 'best']}

**Explanation:

Using Dictionary and Loops

This method builds the result dictionary manually by checking key existence.

Python `

d = {'gfg': [1, 2, 3], 'is': [1, 4], 'best': [4, 2]}

res = {} for key, vals in d.items(): for v in vals: if v in res: res[v].append(key) else: res[v] = [key] print( res)

`

Output

{1: ['gfg', 'is'], 2: ['gfg', 'best'], 3: ['gfg'], 4: ['is', 'best']}

**Explanation:

Using setdefault()

setdefault() method helps avoid key existence checks.

Python `

d = {'gfg': [1, 2, 3], 'is': [1, 4], 'best': [4, 2]}

res = {} for key, vals in d.items(): for v in vals: res.setdefault(v, []).append(key)

print( res)

`

Output

{1: ['gfg', 'is'], 2: ['gfg', 'best'], 3: ['gfg'], 4: ['is', 'best']}

**Explanation: