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 leve…


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.

image

Creating OrderedDict

Since, it is a dict sub-class. It can leverage all the functionalities of dictionary.
imageLet'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 ,

  1. LastInFirstOut(LIFO) order if last is true. That is to say, last pair is popped.(default)
  2. 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


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » Python’s Collections Module: OrderdDict." Kathan Vakharia | Sciencx - Thursday June 17, 2021, https://www.scien.cx/2021/06/17/pythons-collections-module-orderddict/
HARVARD
Kathan Vakharia | Sciencx Thursday June 17, 2021 » Python’s Collections Module: OrderdDict., viewed ,<https://www.scien.cx/2021/06/17/pythons-collections-module-orderddict/>
VANCOUVER
Kathan Vakharia | Sciencx - » Python’s Collections Module: OrderdDict. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/06/17/pythons-collections-module-orderddict/
CHICAGO
" » Python’s Collections Module: OrderdDict." Kathan Vakharia | Sciencx - Accessed . https://www.scien.cx/2021/06/17/pythons-collections-module-orderddict/
IEEE
" » Python’s Collections Module: OrderdDict." Kathan Vakharia | Sciencx [Online]. Available: https://www.scien.cx/2021/06/17/pythons-collections-module-orderddict/. [Accessed: ]
rf:citation
» Python’s Collections Module: OrderdDict | Kathan Vakharia | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.