Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a dictionary in half?

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.

like image 200
user1728853 Avatar asked Oct 20 '12 12:10

user1728853


People also ask

Can I split dictionary in Python?

Method 1: Split dictionary keys and values using inbuilt functions. Here, we will use the inbuilt function of Python that is . keys() function in Python, and . values() function in Python to get the keys and values into separate lists.

How do you split a dictionary by key in Python?

Use data. viewkeys() if you are using Python 2 still. Dictionary views give you a set-like object, on which you can then use set operations; & gives you the intersection.

How do you slice a dictionary in Python?

Given dictionary with value as lists, slice each list till K. Input : test_dict = {“Gfg” : [1, 6, 3, 5, 7], “Best” : [5, 4, 2, 8, 9], “is” : [4, 6, 8, 4, 2]}, K = 3 Output : {'Gfg': [1, 6, 3], 'Best': [5, 4, 2], 'is': [4, 6, 8]} Explanation : The extracted 3 length dictionary value list.

Can a separate dictionary be used as a key?

A dictionary or a list cannot be a key. Values, on the other hand, can literally be anything and they can be used more than once.


2 Answers

This would work, although I didn't test edge-cases:

>>> d = {'key1': 1, 'key2': 2, 'key3': 3, 'key4': 4, 'key5': 5} >>> d1 = dict(d.items()[len(d)/2:]) >>> d2 = dict(d.items()[:len(d)/2]) >>> print d1 {'key1': 1, 'key5': 5, 'key4': 4} >>> print d2 {'key3': 3, 'key2': 2} 

In python3:

d = {'key1': 1, 'key2': 2, 'key3': 3, 'key4': 4, 'key5': 5} d1 = dict(list(d.items())[len(d)//2:]) d2 = dict(list(d.items())[:len(d)//2]) 

Also note that order of items is not guaranteed

like image 125
jone Avatar answered Sep 18 '22 06:09

jone


Here's a way to do it using an iterator over the items in the dictionary and itertools.islice:

import itertools  def splitDict(d):     n = len(d) // 2          # length of smaller half     i = iter(d.items())      # alternatively, i = d.iteritems() works in Python 2      d1 = dict(itertools.islice(i, n))   # grab first n items     d2 = dict(i)                        # grab the rest      return d1, d2 
like image 39
Blckknght Avatar answered Sep 22 '22 06:09

Blckknght