获取OrderedDict的前100个元素

8

preresult 是一个 OrderedDict()

我想要保存其中的前100个元素。或者保留 preresult 但删除除前100个元素以外的其它所有元素。

其结构如下:

stats = {'a':   {'email1':4, 'email2':3}, 
         'the': {'email1':2, 'email3':4},
         'or':  {'email1':2, 'email3':1}}
islice对此有用吗?我的告诉我itertools.islice没有items
4个回答

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

@KurzedMetal,你需要将它转换为列表,然后才能使用常规切片。islice更有效率,因为它可以跳过不需要的项目。 - Mark Ransom
抱歉,我的错误 :P 我确实需要重新阅读itertools和collections文档。 - KurzedMetal
@senderle,它说OrderDict没有iteritems。我使用的是Python 3.2。 - juju

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是a的切片版本

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

0

我们不能只将列表转换为具有键和值的字典,然后按需滑动,然后再放回有序字典中吗?

这是我如何做到的。

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个项目,并仅保留前5个项目:

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

我执行了 print(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}}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接