You can first "flatten" the dict of lists into pairs of (key, value_from_list)
. Then you can simply iterate a list in chunks. The tricky part is just making the chunks back into a dict of lists (turn [("key1", "a"), ("key1", "b")]
into {"key1": ["a", "b"]}
). For that we will use a defaultdict
and iterate over the chunks:
from collections import defaultdict
def chunker(d, chunk_size):
flat = [(key, value) for key, l in d.items() for value in l]
for pos in range(0, len(flat), chunk_size):
chunk = defaultdict(list)
for key, value in flat[pos:pos + chunk_size]:
chunk[key].append(value)
yield dict(chunk)
And running it as:
my_dict = {
"key1": ["a","b","c","d"],
"key2": ["e","f","g","h"],
}
for chunk in chunker(my_dict, 3):
print(chunk)
Will give:
{'key1': ['a', 'b', 'c']}
{'key1': ['d'], 'key2': ['e', 'f']}
{'key2': ['g', 'h']}
If you want to go the extra mile of saving the creation of the flat
list, you can make it a generator instead (flat = ((key, value) for key, l in d.items() for value in l)
) and then follow how to Iterate an iterator by chunks (of n) in Python?.