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 OrderedDict mydict = 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 defaultdict def defval(): return 'default value' mydict = defaultdict(defval) mydict['a'] = 1 mydict['b'] = 2 mydict['c'] = 3 for 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 exception print('\n') # it also add it to the dict for 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
.
RELATED TAGS
CONTRIBUTOR
View all Courses