This content originally appeared on DEV Community and was authored by Kathan Vakharia
Why do we need OrderedDict anway?
Since dictionaries in python maintain their insertion order completely after python 3.7+, use case of OrderedDict
is fading away slowly. But still there are some helper methods and functions that we can leverage while using OrderedDicts.
Creating OrderedDict
Since, it is a dict
sub-class. It can leverage all the functionalities of dictionary.
Let's discuss some important methods pertaining to OrderedDict
only.
popitem
method
The popitem(last = True)
method for ordered dictionaries returns and removes a (key, value) pair.
The pairs are returned in ,
- LastInFirstOut(LIFO) order if last is true. That is to say, last pair is popped.(default)
- FirstInFirstOut(FIFO) order if false. That is to say, first pair is popped.
from collections import OrderedDict
ord_dict = OrderedDict({"fname": "The",
"lname": "CodeBlooded",
"founder": "A Geek",
"Ran by": "Geeks"})
last_pair = ord_dict.popitem() # last=True by default
first_pair = ord_dict.popitem(last=False)
print(f'last pair: {last_pair}')
print(f'first pair: {first_pair}')
"""OUTPUT
last pair: ('Ran by', 'Geeks')
first pair: ('fname', 'The')
"""
move_to_end
method
The move_to_end(key, last=True)
moves an existing key to either end of an ordered dictionary.
The item is moved to the right end if last is true (default) or to the beginning if last is false.
from collections import OrderedDict
ord_dict = OrderedDict({"fname": "The",
"lname": "CodeBlooded",
"founder": "A Geek",
"Ran by": "Geeks"})
print(f'Before =>\n{ord_dict}')
# move to right-most end
ord_dict.move_to_end('founder')
# move to left-most end
ord_dict.move_to_end('Ran by', last=False)
print(f'After =>\n{ord_dict}')
"""OUTPUT
Before =>
OrderedDict([('fname', 'The'), ('lname', 'CodeBlooded'),
('founder', 'A Geek'), ('Ran by', 'Geeks')])
After =>
OrderedDict([('Ran by', 'Geeks'), ('fname', 'The'),
('lname', 'CodeBlooded'), ('founder', 'A Geek')])
"""
? KeyError is raised if given key is not present in the dictionary.
And that wraps our discussion on OrderedDict
! If you notice all of Collections classes we discussed till now are dict
subclass, isn't it interesting ? It's testament to how much powerful dictionaries in python are ?
This content originally appeared on DEV Community and was authored by Kathan Vakharia
Kathan Vakharia | Sciencx (2021-06-17T04:54:12+00:00) Python’s Collections Module: OrderdDict. Retrieved from https://www.scien.cx/2021/06/17/pythons-collections-module-orderddict/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.