w3resource

Python: Split a given dictionary of lists into list of dictionaries

Python dictionary: Exercise-47 with Solution

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

Sample Solution:

Python Code:

def list_of_dicts(marks):
    keys = marks.keys()
    vals = zip(*[marks[k] for k in keys])
    result = [dict(zip(keys, v)) for v in vals]
    return result

marks = {'Science': [88, 89, 62, 95], 'Language': [77, 78, 84, 80]}
print("Original dictionary of lists:")
print(marks)
print("\nSplit said dictionary of lists into list of dictionaries:")
print(list_of_dicts(marks))

Sample Output:

Original dictionary of lists:
{'Science': [88, 89, 62, 95], 'Language': [77, 78, 84, 80]}

Split said dictionary of lists into list of dictionaries:
[{'Science': 88, 'Language': 77}, {'Science': 89, 'Language': 78}, {'Science': 62, 'Language': 84}, {'Science': 95, 'Language': 80}]

Pictorial Presentation:

Python Dictionary: Split a given dictionary of lists into list of dictionaries.

Flowchart:

Flowchart: Split a given dictionary of lists into list of dictionaries.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to create a dictionary grouping a sequence of key-value pairs into a dictionary of lists.
Next: Write a Python program to remove a specified dictionary from a given list.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Free up Memory:

  • Manual garbage collection can be performed on timely or event based mechanism.
import gc
collected_objects = gc.collect()