Skip to content

Instantly share code, notes, and snippets.

@avalanchy
Last active November 9, 2020 13:41
Show Gist options
  • Save avalanchy/ae9ca87faaffcf411a15d8da1185baf3 to your computer and use it in GitHub Desktop.
Save avalanchy/ae9ca87faaffcf411a15d8da1185baf3 to your computer and use it in GitHub Desktop.
python 2/3 chunk_dict utility
from types import GeneratorType
import six
def chunk_dict(dict_, size):
chunk = {}
for i, (key, val) in enumerate(six.iteritems(dict_), start=1):
chunk[key] = val
if i % size == 0:
yield chunk
chunk = {}
if chunk:
yield chunk
res1 = chunk_dict({}, 2)
assert isinstance(res1, GeneratorType)
res2 = list(chunk_dict({"a": 1, "b": 2, "c": 3}, 2))
assert len(res2) == 2
assert len(res2[0]) == 2
assert len(res2[1]) == 1
res3 = list(chunk_dict({"a": 1, "b": 2, "c": 3, "d": 4}, 2))
assert len(res3) == 2
assert len(res3[0]) == 2
assert len(res3[1]) == 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment