Getting Started With OrderedDict
00:22 If you remove an item and reinsert it, then the item is being added at the end of the dictionary. Being a dictionary subclass means that it inherits all the methods a regular dictionary provides.
Unlike standard dictionaries,
OrderedDict isn’t a built-in type, so the first step to create an
OrderedDict object is to import the class from
collections. There are several ways to create ordered dictionaries, and most of them are identical to how you create a regular dictionary object.
Then you create an empty ordered dictionary by instantiating
OrderedDict without providing arguments to the constructor. You can add key-value pairs to the dictionary by providing a key in square brackets (
) and assigning a value to that key.
The order of items in the
OrderedDict objects matches the order in the original dictionary. On the other hand, if you’re using a version of Python lower than 3.6, then the order of items is unknown.
02:59 Since dictionaries in Python 3.5 don’t remember the order of their items, you don’t know the order in the resulting ordered dictionary until the object is created. From this point on, the order is maintained.
Since Python 3.6, functions retain the order of keyword arguments passed in a call, so the order of the items in the
OrderedDict matches the order in which you passed the keyword arguments to the constructor. In earlier Python versions, that order is unknown. Finally,
OrderedDict also provides the
.fromkeys() method, which creates a new dictionary from an iterable of keys and sets all its values to a common value.
If you update the value of a given key in an ordered dictionary, then the key isn’t moved, but assigned the new value in place. In the same way, if you use
.update() to modify the value of an existing key-value pair, then the dictionary remembers the position of the key and assigns the updated value to it.
Become a Member to join the conversation.