Python Practice › Dictionary Programs › Program 75
Pair keys with their single list item
Write a Python program to turn {key: [value]} into one dictionary per combination.
Input
{1: ["Virat Kohli"], 2: ["Rohit Sharma"], 3: ["Hardik Pandya"]}Output
[{1: 'Virat Kohli', 2: 'Rohit Sharma', 3: 'Hardik Pandya'}]Approach
itertools.productover the value lists, zipped back with the keys.
Solution
from itertools import product d = {1: ["Virat Kohli"], 2: ["Rohit Sharma"], 3: ["Hardik Pandya"]}print([dict(zip(d, combo)) for combo in product(*d.values())])Output
[{1: 'Virat Kohli', 2: 'Rohit Sharma', 3: 'Hardik Pandya'}]Line by line
Line 4
With one item per list there is exactly one combination; longer lists would produce every pairing.
Learn the concept
New to this topic? Read the lesson, then come back.