How to iterate only over the first n elements of a very large dictionary in python ?

Active March 24, 2021    /    Viewed 520    /    Comments 0    /    Edit


Example of how to iterate over the first n elements for a large dictionary in python:

Create a dictionary

Let's assume we have a very large dictionary in python:

d = {}

for i in range(1000000):
    d[i] = random.randint(1,10)

and that we want to print only the first n elements.

Iterate only over the first n elements

A solution is then to use islice,

from itertools import islice

for item in islice(d.items(), 5):
    print('Key:{} Value:{}'.format(item[0], item[1]))

returns

Key:0 Value:1
Key:1 Value:7
Key:2 Value:10
Key:3 Value:7
Key:4 Value:8

Note: islice can be used to slice any part of the dictionary islice(dict,start, end):

from itertools import islice

for item in islice(d.items(), 10,15):
    print('Key:{} Value:{}'.format(item[0], item[1]))

returns

Key:10 Value:3
Key:11 Value:1
Key:12 Value:4
Key:13 Value:8
Key:14 Value:10

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount