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:
- **defaultdict(list): creates a dictionary where each key automatically starts with an empty list.
- **res[v].append(key): appends the current key to the list of keys associated with value v.
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:
- **for key, vals in d.items(): iterates over each key–value pair.
- **if v in res: checks if the value already exists in the result dictionary.
- **res[v].append(key): adds the current key to the existing list of keys for that value.
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:
- **for key, vals in d.items(): Iterates through each key-value pair in the dictionary.
- **for v in vals: For every value, adds its corresponding key to res.
- **res.setdefault(v, []).append(key): Uses setdefault() to handle missing keys efficiently.