...

/

Disorder Within Order

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 OrderedDict
dictionary = 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 order
another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a';
class DictWithHash(dict):
"""
A dict that also implements __hash__ magic.
"""
__hash__ = lambda self: 0
class OrderedDictWithHash(OrderedDict):
"""
An OrderedDict that also implements __hash__ magic.
"""
__hash__ = lambda self: 0
print(dictionary == ordered_dict) # If a == b
print(dictionary == another_ordered_dict) # and b == c
print(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 ...