Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first 100 elements of OrderedDict

preresult is an OrderedDict().

I want to save the first 100 elements in it. Or keep preresult but delete everything other than the first 100 elements.

The structure is like this

stats = {'a':   {'email1':4, 'email2':3}, 
         'the': {'email1':2, 'email3':4},
         'or':  {'email1':2, 'email3':1}}

Will islice work for it? Mine tells itertool.islice does not have items

like image 686
juju Avatar asked May 08 '12 17:05

juju


1 Answers

Here's a simple solution using itertools:

>>> import collections
>>> from itertools import islice
>>> preresult = collections.OrderedDict(zip(range(200), range(200)))
>>> list(islice(preresult, 100))[-10:]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

This returns only keys. If you want items, use iteritems (or just items in Python 3):

>>> list(islice(preresult.iteritems(), 100))[-10:]
[(90, 90), (91, 91), (92, 92), (93, 93), (94, 94), (95, 95), (96, 96), (97, 97), (98, 98), (99, 99)]
like image 146
senderle Avatar answered Oct 21 '22 17:10

senderle