Pair keys with their single list item

EasyDictionary Programs · 75 of 94

Write a Python program to turn {key: [value]} into one dictionary per combination.

Advertisement
Input
{1: ["Virat Kohli"], 2: ["Rohit Sharma"], 3: ["Hardik Pandya"]}
Output
[{1: 'Virat Kohli', 2: 'Rohit Sharma', 3: 'Hardik Pandya'}]

Approach

  1. itertools.product over the value lists, zipped back with the keys.

Solution

Python
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.

Advertisement

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs