Alex Rivera | Logout

Split a dictionary in half?

Asked 2012-10-20T12:17:59.787
35

What is the best way to split a dictionary in half?

d = {'key1': 1, 'key2': 2, 'key3': 3, 'key4': 4, 'key5': 5}

I'm looking to do this:

d1 = {'key1': 1, 'key2': 2, 'key3': 3}
d2 = {'key4': 4, 'key5': 5}

It does not matter which keys/values go into each dictionary. I am simply looking for the simplest way to divide a dictionary into two.

Edit
Report

1 Answer

1

We can do this efficiently with itertools.zip_longest() (note this is itertools.izip_longest() in 2.x):

from itertools import zip_longest
d = {'key1': 1, 'key2': 2, 'key3': 3, 'key4': 4, 'key5': 5}
items1, items2 = zip(*zip_longest(*[iter(d.items())]*2))
d1 = dict(item for item in items1 if item is not None)
d2 = dict(item for item in items2 if item is not None)

Which gives us:

>>> d1
{'key3': 3, 'key1': 1, 'key4': 4}
>>> d2
{'key2': 2, 'key5': 5}
answered 2012-10-20T12:36:01.440

Your Answer