collections | OrderedDict constructor
Start your free 7-days trial now!
An OrderedDict
object is a subclass of a standard dict
object. OrderedDict
objects retain the order of keys in the order they were inserted (which dict
objects also now support since Python 3.6).
Key advantages of OrderedDict
over dict
:
Methods available specifically for reordering items such as
move_to_end(~)
andpopitem(~)
Performing equality tests where the order of items in the dictionary is important
Backward compatibility for versions earlier than Python 3.6
Parameters
1. items
| sequence
| optional
Key-value pairs to initialize the OrderedDict
object with.
Return value
An OrderedDict
object.
Examples
Basic usage
To initialize an empty OrderedDict
object:
from collections import OrderedDictod = OrderedDict() #Initialise OrderedDict object
#Add key-value pairs to the empty OrderedDictod['key1'] = 1od['key2'] = 2print(od)
OrderedDict([('key1', 1), ('key2', 2)])
Keyword arguments
To initialize an OrderedDict
using keyword arguments:
from collections import OrderedDictod = OrderedDict(key1=1, key2=2) #Initialise OrderedDict objectprint(od)
OrderedDict([('key1', 1), ('key2', 2)])
Sequence
To initialize an OrderedDict
using a sequence of key-value pairs:
from collections import OrderedDictod = OrderedDict([('key1', 1), ('key2', 2)])print(od)
OrderedDict([('key1', 1), ('key2', 2)])
Set
To initialize an OrderedDict
using a set
:
from collections import OrderedDictod = OrderedDict({("key3", 3), ("key2", 2), ("key1", 1)})print(od)
OrderedDict([('key1', 1), ('key2', 2), ('key3', 3)])
When using a set
to initialize an OrderedDict, the order of items is unknown until the OrderedDict
is created.
Dictionary
To initialize an OrderedDict using a dict
:
from collections import OrderedDictod = OrderedDict({"key1": 1, "key2": 2, "key3": 3})print(od)
OrderedDict([('key1', 1), ('key2', 2), ('key3', 3)])
If you are using Python 3.6 or greater, the order of items in OrderedDict
will be the same as the order of items in the dict
used to initialize. In versions lower than Python 3.6, the order of items is not known until the OrderedDict
is initialized.