2012-05-08 41 views
8

preresultOrderedDict()獲取OrderedDict的前100個元素

我想保存其中的前100個元素。或者保留preresult,但刪除前100個元素以外的所有內容。

的結構是這樣的

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

將islice爲它工作礦井告訴itertool.islice沒有items

回答

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

@KurzedMetal的切片版本,你需要將其轉換爲一個列表之前常規切片將工作。 'islice'效率更高,因爲它可以跳過不需要的項目。 –

+0

對不起,我的錯誤:我真的需要重讀itertools和集合文檔。 – KurzedMetal

+0

@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是