Python Practice › Dictionary Programs › Program 92
Split a dictionary into chunks
Write a Python program to split a dictionary into dictionaries of n items.
Input
{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6}, n = 3Output
[{'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5, 'f': 6}]Approach
- Slice the list of items in steps of n.
Solution
d = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6}n = 3items = list(d.items())print([dict(items[i:i + n]) for i in range(0, len(items), n)])Output
[{'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5, 'f': 6}]Learn the concept
New to this topic? Read the lesson, then come back.