OrderedDict
and defaultdict
are both subclasses of dict
. They have different uses.
OrderedDict
keeps the elements in the order that they were in when they were first inserted.
If we remove an element and re-add it, the element will be pushed to the back. If an element’s key changes, the position does not change.
from collections import OrderedDictmydict = OrderedDict([('a', '1'), ('b', '2'), ('c', '3')])for k in mydict.items():print(k)print('\n')mydict.pop('b')mydict['b'] = '2'for k in mydict.items():print(k)
In the code above, we created an OrderedDict
, added elements to it, and then printed them. Then, we removed one item and reentered it in the dict
. It is now at the last index because the order of entry has changed.
A defaultdict
is a useful subclass that doesn’t raise a KeyError
exception when trying to access an undefined key. However, you must define a function that defines what you want to happen when a key is searched for that doesn’t exist. Let’s look at an example:
from collections import defaultdictdef defval():return 'default value'mydict = defaultdict(defval)mydict['a'] = 1mydict['b'] = 2mydict['c'] = 3for k in mydict.items():print(k)print('\n')# if we try to get 'd'print(mydict['d'])# with a 'generic' dict this will raise a KeyError exceptionprint('\n')# it also add it to the dictfor k in mydict.items():print(k)
In the code above, we defined a function (defval()
) that returns “default value” when a KeyError
exception would normally be raised. Then, we defined a defaultdict
, added items to it, and printed them. Then, we tried to get d
, which is a value that’s not present. This also adds that value to the dict
.