Professional Documents
Culture Documents
dict, many searches happen with no collisions, and the average number of collisions
per search is between one and two. Under normal usage, even the unluckiest keys can
be found after a handful of collisions are resolved.
Knowing the internals of the dict implementation we can explain the strengths and
limitations of this data structure and all the others derived from it in Python. We are
now ready to consider why Python dicts behave as they do.
1. It supports the hash() function via a hash() method that always returns the same
value over the lifetime of the object.
2. It supports equality via an eq() method.
3. If a == b is True then hash(a) == hash(b) must also be True.
User-defined types are hashable by default because their hash value is their id() and
they all compare not equal.
WOW! eBook
www.wowebook.org
For user-defined types, the __slots__ class attribute changes the storage of instance
attributes from a dict to a tuple in each instance. This will be discussed in “Saving Space
with the __slots__ Class Attribute” on page 264 (Chapter 9).
Keep in mind we are talking about space optimizations. If you are dealing with a few
million objects and your machine has gigabytes of RAM, you should postpone such
optimizations until they are actually warranted. Optimization is the altar where main‐
tainability is sacrificed.
d1 = dict(DIAL_CODES)
print('d1:', d1.keys())
d2 = dict(sorted(DIAL_CODES))
WOW! eBook
www.wowebook.org