Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Split a python dictionary equally based on keys
def split_dict_equally(input_dict, chunks=2):
"Splits dict by keys. Returns a list of dictionaries."
# prep with empty dicts
return_list = [dict() for idx in xrange(chunks)]
idx = 0
for k,v in input_dict.iteritems():
return_list[idx][k] = v
if idx < chunks-1: # indexes start at 0
idx += 1
else:
idx = 0
return return_list
@lemurchik

This comment has been minimized.

Copy link

lemurchik commented Jun 9, 2015

May be it's late, but better to do:

return_list = [dict()] * chunks
@rseaman

This comment has been minimized.

Copy link

rseaman commented Mar 18, 2018

For anyone finding this in the future, at least in Python 3 doing:
return_list = [dict() for idx in range(chunks)]
IS NOT the same as
return_list = [dict()] * chunks

The first works as expected in most cases, with individual dictionaries in a list (the only difference is using range instead of xrange in Python3). The second will create a list of references to the same dictionary. Any operations on any of the items will therefore cause a change to "all items", being just a reference to the same item multiple times.

@cy526

This comment has been minimized.

Copy link

cy526 commented May 24, 2018

return_list = [dict()] * chunks is wrong. You will have a list of the same dict object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.