获取OrderedDict的前100个元素

时间:2012-05-08 17:42:37

标签: python python-3.x

preresultOrderedDict()

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

结构就像这样

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

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

4 个答案:

答案 0 :(得分: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]

这只返回键。如果您需要项目,请使用iteritems(或仅使用Python 3中的items):

>>> 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)]

答案 1 :(得分:3)

您可以对OrderedDict的键进行切片并复制它。

from collections import OrderedDict

a = OrderedDict()
for i in xrange(10):
    a[i] = i*i

b = OrderedDict()
for i in a.keys()[0:5]:
    b[i] = a[i]

b是

的切片版本

答案 2 :(得分:1)

for k, v in list(od.items())[:100]:
   pass

答案 3 :(得分:0)

我们不能只是将列表转换为包含键和值的字典,然后根据需要滑动它,然后将其放回orderedDict中吗?

这就是我的做法。

from collections import OrderedDict

#defined an OrderedDict()

stats = OrderedDict()

#loading the ordered list with 100 keys
for i in range(100):
    stats[str(i)] = {'email'+str(i):i,'email'+str(i+1):i+1}

#Then slicing the first 20 elements from the OrderedDict
#I first convert it to a list, then slide, then put it back as an OrderedDict

st = OrderedDict(list(stats.items())[:20])

print  (stats)

print (st)

其输出如下。我将第一个减少到10个项目,并将其切成仅前五个项目:

OrderedDict([('0', {'email0': 0, 'email1': 1}), ('1', {'email1': 1, 'email2': 2}), ('2', {'email2': 2, 'email3': 3}), ('3', {'email3': 3, 'email4': 4}), ('4', {'email4': 4, 'email5': 5}), ('5', {'email5': 5, 'email6': 6}), ('6', {'email6': 6, 'email7': 7}), ('7', {'email7': 7, 'email8': 8}), ('8', {'email8': 8, 'email9': 9}), ('9', {'email9': 9, 'email10': 10})])

OrderedDict([('0', {'email0': 0, 'email1': 1}), ('1', {'email1': 1, 'email2': 2}), ('2', {'email2': 2, 'email3': 3}), ('3', {'email3': 3, 'email4': 4}), ('4', {'email4': 4, 'email5': 5})])

我做了打印(dict(st))来得到这个:

{'0': {'email0': 0, 'email1': 1}, '1': {'email1': 1, 'email2': 2}, '2': {'email2': 2, 'email3': 3}, '3': {'email3': 3, 'email4': 4}, '4': {'email4': 4, 'email5': 5}}