OrderedDict and defaultdict
In the previous lesson, I concentrated on the
dict type, which is built into Python. In this lesson, I’m going to cover
defaultdict, which are part of the
collections standard library.
dict type isn’t the only kind of dictionary that Python provides. There are others in the standard library.
OrderedDict, part of the
collections library, remembers the insertion order of the keys.
It also provides some other useful functionality as well. It supports iteration over the dictionary using Python’s built-in
reversed() method, and then provides two additional methods that the standard dictionary doesn’t have.
.move_to_end() moves a key inside of
OrderedDict to the end of the listing, as if it was the last thing inserted.
.popitem()—although that’s supported by the standard dictionary type, the
OrderedDict type takes an additional parameter, allowing you to pop either the first item or the last item off the
Depending on how closely you’ve been following along with the changes to the dictionary in CPython implementations,
OrderedDict might be a bit of a surprise that it exists. And that’s because as of Python 3.6,
dict type itself maintained order.
It did that as part of how it was implemented but wasn’t part of the language specification. Python 3.7 changed the specification so that maintaining the order was a requirement of the
Although almost everything that I’m about to show you is possible with the built-in
dict type in Python 3.9—the version of the language I’m using—I’m going to explicitly use
collections in case you’re using an older version and need to follow along.
The constructor for the
OrderedDict class takes an arbitrary number of arguments. It automatically creates a dictionary mapping the keys to the values of those arguments passed in. And there’s the repr for it.
Notice that it displays it like a list, showing that
3 were inserted, in that order. Like a regular dictionary, you can use the square bracket notation to insert items into the dictionary.
Similar to the built-in
OrderedDict supports the
.keys() method. And the
reversed() function is also supported on the dictionary. This returns an iterator, which, if I turn into a list, shows you the value of the keys in reverse of insertion order.
04:30 By using a default dictionary configured with an empty list, the first use of an empty key is initialized to an empty list. This means you don’t have to write the additional code checking whether or not the key exists in the dictionary, and if it doesn’t, add the key to the dictionary with an empty list and then add the item that you were intending to put in in the first place.
Let me just add one more thing to
"dogs" here, and then you can reference the key specifically and get the list resulting. You can initialize your
defaultdict with just about anything, although the list is the most common thing I’ve seen out there in code.
Become a Member to join the conversation.