Which keys contain each value

EasyDictionary Programs · 81 of 94

Write a Python program to show, for each value, the keys whose lists contain it.

Advertisement
Input
{"xyz": [20, 40], "abc": [10, 20]}
Output
{20: ['xyz', 'abc'], 40: ['xyz'], 10: ['abc']}

Approach

  1. Invert into defaultdict(list).

Solution

Python
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']}
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs