打印到或来自第n个键OrderedDict()python

时间:2017-01-30 18:33:15

标签: python ordereddictionary

如何在python中打印OrderedDict的前10个或最后10个键值组?

这个

$comments = $job->comments->merge($job->customer->comments)->sortByDate('created_at', true);

或者这个:

for item in my_ordereddict[:5]:
    print item

不行。 有什么帮助吗?

2 个答案:

答案 0 :(得分:2)

我会使用itertools.islice切片OrderedDict.items()视图

from itertools import islice
from collections import OrderedDict

o = OrderedDict()
for i in range(100):
    o[i] = 2*i

for i in islice(o.items(), 0, 10):
    print(i)

输出:

(0, 0)
(1, 2)
(2, 4)
(3, 6)
(4, 8)
(5, 10)
(6, 12)
(7, 14)
(8, 16)
(9, 18)

答案 1 :(得分:1)

from collections import OrderedDict


if __name__ == '__main__':
    od = OrderedDict([["one", 1], ["two", 2], ["three", 3], ["four", 4], ["five", 5], ["six", 6]])
    for i in od.keys()[0:3]:
        print od[i]