Computer >> Computer tutorials >  >> Programming >> Python

How to truncate a Python dictionary at a given length?


The itertools module included in standard Python distribution contains many iterator building blocks inspired by functional languages like Closure, Haskell etc. One of the functions in this module is islice(). It returns an iterator by selecting specific elements from iterable. The syntax of islice() is as follows:

islice(sequence, start, stop, step)

Following illustration truncates given dictionary by selecting only first three items

>>> D1={"pen":25, "pencil":10, "book":100, "sharpner":5, "eraser":5}
>>> import itertools
>>> D2=dict(itertools.islice(D1.items(),3))
>>> D2
{'pen': 25, 'pencil': 10, 'book': 100}