Python Practice › Dictionary Programs › Program 58
Dict of lists to list of dicts
Write a Python program to split a dictionary of lists into a list of dictionaries.
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
zip(*d.values())gives one row per position.
Solution
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.