Example of how to iterate over the first n elements for a large dictionary in python:
Table of contents
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 islicefor item in islice(d.items(), 5):print('Key:{} Value:{}'.format(item[0], item[1]))
returns
Key:0 Value:1Key:1 Value:7Key:2 Value:10Key:3 Value:7Key:4 Value:8
Note: islice can be used to slice any part of the dictionary islice(dict,start, end):
from itertools import islicefor item in islice(d.items(), 10,15):print('Key:{} Value:{}'.format(item[0], item[1]))
returns
Key:10 Value:3Key:11 Value:1Key:12 Value:4Key:13 Value:8Key:14 Value:10
