Trimming dictionaries

You could try

d = dict(d.items()[:MAX_RESULTS])

You can use itertools.islice on dict.iteritems.

dict.iteritems() returns an iterator in py2.x, you can slice that iterator using itertools.islice and pass it to dict() to get the new dict.

Demo:

>>> from itertools import islice
>>> d = dict.fromkeys(range(10))
>>> dict(islice(d.iteritems(), 5))
{0: None, 1: None, 2: None, 3: None, 4: None}

Timings:

>>> d = dict.fromkeys(range(100))
>>> %timeit from itertools import islice;dict(islice(d.iteritems(), 10)) #winner
10000 loops, best of 3: 10.7 us per loop
>>> %timeit dict(d.items()[0: 10])
100000 loops, best of 3: 10.9 us per loop

>>> d = dict.fromkeys(range(10**5))
>>> %timeit from itertools import islice;dict(islice(d.iteritems(), 1000)) #winner
1000 loops, best of 3: 106 us per loop
>>> %timeit dict(d.items()[0: 1000])
100 loops, best of 3: 20 ms per loop

This returns the 1st 2 elements of 4 from a dictionary (in python 2.6)

elems = {'a': 2, 'b': 7, 'c': 3, 'd': 9}
dict((k, v) for k, v in elems.items() if k in elems.keys()[:2])

Tags:

Python