python split dict into chunks

Solutions on MaxInterview for python split dict into chunks by the best coders in the world

showing results for - "python split dict into chunks"
Emanuele
29 Apr 2018
1# Since the dictionary is so big, it would be better to keep
2# all the items involved to be just iterators and generators, like this
3
4from itertools import islice
5
6def chunks(data, SIZE=10000):
7    it = iter(data)
8    for i in range(0, len(data), SIZE):
9        yield {k:data[k] for k in islice(it, SIZE)}
10        
11# Sample run:
12for item in chunks({i:i for i in range(10)}, 3):
13    print item
14    
15# Output
16# {0: 0, 1: 1, 2: 2}
17# {3: 3, 4: 4, 5: 5}
18# {8: 8, 6: 6, 7: 7}
19# {9: 9}