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


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