Reputation: 454
Suppose I have a simple Python dictionary that looks like this:
{'location1': [1], 'location2': [1], 'location3': [1], 'location4': [1], 'location5': [1]}
My goal is to split this dictionary into a list of dictionaries, that are all of specific size N, except for the size of the last dictionary, which may be smaller than N if there are not enough elements in the dictionary. So N = 2 would yield:
[{'location1': [1], 'location2': [1]}, {'location3': [1], 'location4': [1]}, {'location5': [1]}]
While N = 3 would yield:
[{'location1': [1], 'location2': [1], 'location3': [1]}, {'location4': [1]}, 'location5': [1]}]
I have tried but can not find a way to do this. Note that the locations in each of the slices/batches does not matter to me, as long as they are equally distributed among slices.
Upvotes: 0
Views: 731
Reputation: 1352
try something like this:
n = 2 # the desired # of parts
items = list(d.items())
y = [dict(items[x:x+n+1]) for x in range(0, len(d), n+1)]
Upvotes: 3