How do you get the first 3 elements in Python OrderedDict?

本秂侑毒 提交于 2019-12-03 11:05:15

Let's create a simple OrderedDict:

>>> from collections import OrderedDict
>>> od = OrderedDict(enumerate("abcdefg"))
>>> od
OrderedDict([(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g')])

To return the first three keys, values or items respectively:

>>> list(od)[:3]
[0, 1, 2]
>>> list(od.values())[:3]
['a', 'b', 'c']
>>> list(od.items())[:3]
[(0, 'a'), (1, 'b'), (2, 'c')]

To remove everything except the first three items:

>>> while len(od) > 3:
...     od.popitem()
... 
(6, 'g')
(5, 'f')
(4, 'e')
(3, 'd')
>>> od
OrderedDict([(0, 'a'), (1, 'b'), (2, 'c')])

You can use this iterative method to get the job done.

x = 0
for i in ordered_dict:
    if x > 3:
        del ordered_dict[i]
    x += 1

First, you just make a counter variable, x, and assign it to 0. Then you cycle through the keys in ordered_dict. You see how many items have been checked by seeing it x is greater than 3, which is the number of values you want. If 3 items have already been checked, you delete that item from ordered_dict.


Here is a cleaner, alternative method (thanks to the comments)

for i, k in enumerate(ordered_dict):
    if i > 2:
        del ordered_dict[k]

This works by using enumerate to assign a number to each key. Then it checks if that number is less than two (0, 1, or 2). If the number is not 0, 1, or 2 (these will be the first three elements), then that item in the dictionary will be deleted.

It's not different from other dicts:

d = OrderedDict({ x: x for x in range(10) })

i = d.iteritems()
a = next(i)
b = next(i)
c = next(i)

d = OrderedDict([a,b,c])
# or
d.clear()
d.update([a,b,c])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!