我们不能将列表转换为带有键和值的字典,然后根据需要滑动它,然后将其放回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 个项目,并将其切成前 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}}