Search⌘ K
AI Features

Disorder Within Order

Explore how Python dictionaries and OrderedDicts handle equality and order differently, causing unexpected behaviors in sets. Understand why changing insertion order impacts set length, and learn about the implications of intransitive equality on dictionary and set operations in Python.

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.

Python 3.5
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.

C++
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 OrderedDictWithHash. ...