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?
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?
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 del
ete 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])