Python Practice › Dictionary Programs › Program 81
Which keys contain each value
Write a Python program to show, for each value, the keys whose lists contain it.
Input
{"xyz": [20, 40], "abc": [10, 20]}Output
{20: ['xyz', 'abc'], 40: ['xyz'], 10: ['abc']}Approach
- Invert into
defaultdict(list).
Solution
from collections import defaultdict d = {"xyz": [20, 40], "abc": [10, 20]}inverted = defaultdict(list)for key, values in d.items(): for v in values: inverted[v].append(key)print(dict(inverted))Output
{20: ['xyz', 'abc'], 40: ['xyz'], 10: ['abc']}Learn the concept
New to this topic? Read the lesson, then come back.