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
:To return the first three keys, values or items respectively:
To remove everything except the first three items:
It's not different from other dicts:
You can use this iterative method to get the job done.
First, you just make a counter variable,
x
, and assign it to 0. Then you cycle through the keys inordered_dict
. You see how many items have been checked by seeing itx
is greater than 3, which is the number of values you want. If 3 items have already been checked, youdel
ete that item fromordered_dict
.Here is a cleaner, alternative method (thanks to the comments)
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.