获取OrderedDict的前100个元素

juj*_*uju 8 python python-3.x

preresult是一个OrderedDict().

我想保存前100个元素.或者保留preresult但删除除前100个元素之外的所有内容.

结构是这样的

stats = {'a':   {'email1':4, 'email2':3}, 
         'the': {'email1':2, 'email3':4},
         'or':  {'email1':2, 'email3':1}}
Run Code Online (Sandbox Code Playgroud)

Will islice会为它工作吗?我告诉itertool.islice没有items

sen*_*rle 14

这是一个简单的解决方案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]
Run Code Online (Sandbox Code Playgroud)

这只返回键.如果你想要项目,请使用iteritems(或仅items在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)]
Run Code Online (Sandbox Code Playgroud)