Split a dictionary into chunks

EasyDictionary Programs · 92 of 94

Write a Python program to split a dictionary into dictionaries of n items.

Advertisement
Input
{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6}, n = 3
Output
[{'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5, 'f': 6}]

Approach

  1. Slice the list of items in steps of n.

Solution

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

More dictionary programs

← All 94 Dictionary Programs