Disorder Within Order
We'll cover the following...
How can Python dictionaries be chaotic? They were supposed to keep the order. Let’s see what’s going on.
Press + to interact
from collections import OrderedDictdictionary = dict()dictionary[1] = 'a'; dictionary[2] = 'b';ordered_dict = OrderedDict()ordered_dict[1] = 'a'; ordered_dict[2] = 'b';another_ordered_dict = OrderedDict() # same key-values, different orderanother_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a';class DictWithHash(dict):"""A dict that also implements __hash__ magic."""__hash__ = lambda self: 0class OrderedDictWithHash(OrderedDict):"""An OrderedDict that also implements __hash__ magic."""__hash__ = lambda self: 0print(dictionary == ordered_dict) # If a == bprint(dictionary == another_ordered_dict) # and b == cprint(ordered_dict == another_ordered_dict) # then why isn't c == a ??
Recall that a set consists of only unique elements. Let’s try making a set of these dictionaries and see what happens.
Press + to interact
len({dictionary, ordered_dict, another_ordered_dict})
It makes sense, since dict
and OrderedDict
don’t have __hash__
implemented let’s use our wrapper classes DictWithHash
and ...