collections.OrderedDict
StevenSwiniarski466 total contributions
Published Jul 7, 2022
Contribute to Docs
An OrderedDict is a data type in the collections
module. It is a dict
subclass that tracks the order in which items were added. It offers all the standard dictionary methods as well as two additional methods that deal with the ordering of the OrderedDict
.
Syntax
myOrderedDict = collections.OrderedDict()
Like a regular dictionary, an OrderedDict
can also be initialized with the .fromkeys()
method.
myOrderedDict = collections.OrderedDict.fromkeys(keylist, value)
Additional Methods
In addition to the standard dict
methods, the following are specific to an OrderedDict
:
.popitem(last)
: Returns and removes a key-value pair from theOrderedDict
. The pairs are returned in LIFO (last-in-first-out) order iflast
isTrue
and FIFO (first-in-first-out) order iflast
isFalse
. Thelast
argument is optional and defaults toTrue
..move_to_end(key, last)
: Moves thekey
to one end of theOrderedDict
. Iflast
isTrue
it is moved to the right end (last entered). Otherwise, it is moved to the start (first entered). Thelast
argument is optional and defaults toTrue
.
Codebyte Example
The following example creates an OrderedDict
and rearranges some items in it.
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.