Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,987 questions

51,931 answers

573 users

How to split a dictionary into chunks of size N in Python

2 Answers

0 votes
import itertools

def split_dict(d, n):
    it = iter(d.items())
    while True:
        chunk = dict(list(itertools.islice(it, n)))
        if not chunk:
            break
        yield chunk


data = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9}

for part in split_dict(data, 4):
    print(part)


 
'''
run:
 
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
{'e': 5, 'f': 6, 'g': 7, 'h': 8}
{'i': 9}
 
'''

 



answered 11 hours ago by avibootz
0 votes
def split_dict(d, n):
    items = list(d.items())
    return [dict(items[i:i + n]) for i in range(0, len(items), n)]


data = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9}

for part in split_dict(data, 4):
    print(part)


 
'''
run:
 
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
{'e': 5, 'f': 6, 'g': 7, 'h': 8}
{'i': 9}

'''

 



answered 11 hours ago by avibootz

Related questions

1 answer 125 views
5 answers 305 views
1 answer 133 views
9 answers 798 views
...