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.
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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With