collections.OrderedDict
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.
Contribute to Docs
- 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.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours