What are Ordered dictionaries in Python?


An OrderedDict is a dictionary subclass that remembers the order in which its contents are added, supporting the usual dict methods.If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.

>>> from collections import OrderedDict
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'mango': 2}
>>> od=OrderedDict(d.items())
>>> od
OrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('mango', 2)])
>>> od=OrderedDict(sorted(d.items()))
>>> od
OrderedDict([('apple', 4), ('banana', 3), ('mango', 2), ('pear', 1)])
>>> t=od.popitem()
>>> t
('pear', 1)
>>> od=OrderedDict(d.items())
>>> t=od.popitem()
>>> t
('mango', 2)

Updated on: 02-Mar-2020

356 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements