Chapter 3. Dictionaries and Sets
Python is basically dicts wrapped in loads of syntactic sugar.
Lalo Martins, early digital nomad and Pythonista
We use dictionaries in all our Python programs. If not directly in our code,
then indirectly because the dict
type is a fundamental part of Python’s implementation.
Class and instance attributes, module namespaces,
and function keyword arguments are some of the core Python constructs represented by dictionaries in memory.
The __builtins__.__dict__
stores all built-in types, objects, and functions.
Because of their crucial role, Python dicts are highly optimized—and continue to get improvements. Hash tables are the engines behind Python’s high-performance dicts.
Other built-in types based on hash tables are set
and frozenset
. These offer richer APIs and operators than the sets you may have encountered in other popular languages. In particular, Python sets implement all the fundamental operations from set theory, like union, intersection, subset tests, etc. With them, we can express algorithms in a more declarative way, avoiding lots of nested loops and conditionals.
Here is a brief outline of this chapter:
-
Modern syntax to build and handle
dicts
and mappings, including enhanced unpacking and pattern matching -
Common methods of mapping types
-
Special handling for missing keys
-
Variations of
dict
in the standard library -
The
set
andfrozenset
types -
Implications of hash tables in the behavior of sets and dictionaries
What’s New ...
Get Fluent Python, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.