Created
December 18, 2019 13:11
-
-
Save nz-angel/31890d2c6cb1c9105e677cacc83a1ffd to your computer and use it in GitHub Desktop.
A couple of functions to split a Python dictionary into chunks of equal size
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Allows to split a dictionary into chunks of equal size. If the length of the dictionary is not divisible by the chunk | |
size, the last chunk will be smaller. For example, if the length of the dictionary is 10 and the chunk size is 4, | |
then we'll have three chunks: two of size 4 and one of size 2. | |
The first function returns a list with the dictionaries and the second one creates a generator. | |
""" | |
def split_dictionary(input_dict, chunk_size): | |
res = [] | |
new_dict = {} | |
for k, v in input_dict.items(): | |
if len(new_dict) < chunk_size: | |
new_dict[k] = v | |
else: | |
res.append(new_dict) | |
new_dict = {k: v} | |
res.append(new_dict) | |
return res | |
def gen_split_dictionary(input_dict, chunk_size): | |
new_dict = {} | |
for k, v in input_dict.items(): | |
if len(new_dict) < chunk_size: | |
new_dict[k] = v | |
else: | |
yield new_dict | |
new_dict = {k: v} | |
yield |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment