本文介绍了如何获得Python OrderedDict中的前3个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取Python OrderedDict中的前3个元素?

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

也可以从此字典中删除数据.

Also is it possible to delete data from this dictionary.

例如:如何获取Python OrderedDict中的前三个元素并删除其余元素?

For example: How would I get the first 3 elements in Python OrderedDict and delete the rest of the elements?

推荐答案

让我们创建一个简单的OrderedDict:

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

分别返回前三个:

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

这篇关于如何获得Python OrderedDict中的前3个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 02:47