Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Also is it possible to delete data from this dictionary.

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

like image 800
Michael Smith Avatar asked May 15 '15 02:05

Michael Smith


1 Answers

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')])
like image 76
Zero Piraeus Avatar answered Nov 03 '22 15:11

Zero Piraeus