collections.OrderedDict

StevenSwiniarski's avatar
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 the OrderedDict. The pairs are returned in LIFO (last-in-first-out) order if last is True and FIFO (first-in-first-out) order if last is False. The last argument is optional and defaults to True.
  • .move_to_end(key, last): Moves the key to one end of the OrderedDict. If last is True it is moved to the right end (last entered). Otherwise, it is moved to the start (first entered). The last argument is optional and defaults to True.

Codebyte Example

The following example creates an OrderedDict and rearranges some items in it.

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Python on Codecademy