An Interest In:
Web News this Week
- February 28, 2024
- February 27, 2024
- February 26, 2024
- February 25, 2024
- February 24, 2024
- February 23, 2024
- February 22, 2024
Python's Collections Module: OrderdDict
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 OrderedDictord_dict = OrderedDict({"fname": "The", "lname": "CodeBlooded", "founder": "A Geek", "Ran by": "Geeks"})last_pair = ord_dict.popitem() # last=True by defaultfirst_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 OrderedDictord_dict = OrderedDict({"fname": "The", "lname": "CodeBlooded", "founder": "A Geek", "Ran by": "Geeks"})print(f'Before =>
{ord_dict}')# move to right-most endord_dict.move_to_end('founder')# move to left-most endord_dict.move_to_end('Ran by', last=False)print(f'After =>
{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
Original Link: https://dev.to/kathanvakharia/python-s-collections-module-orderddict-30ia
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To