Dict of lists to list of dicts

EasyDictionary Programs · 58 of 94

Write a Python program to split a dictionary of lists into a list of dictionaries.

Advertisement
Input
{"t20": [50, 40, 30, 45], "odi": [70, 10, 0, 65]}
Output
[{'t20': 50, 'odi': 70}, {'t20': 40, 'odi': 10}, {'t20': 30, 'odi': 0}, {'t20': 45, 'odi': 65}]

Approach

  1. zip(*d.values()) gives one row per position.

Solution

Python
d = {"t20": [50, 40, 30, 45], "odi": [70, 10, 0, 65]}print([dict(zip(d, row)) for row in zip(*d.values())])
Output
[{'t20': 50, 'odi': 70}, {'t20': 40, 'odi': 10}, {'t20': 30, 'odi': 0}, {'t20': 45, 'odi': 65}]

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs