This chapter introduces Python dictionaries as the language’s built-in mapping type, implemented with hash tables. It contrasts them with lists: lists use integer indices and imply positional order, while dictionaries map keys to values and allow keys to be many kinds of objects. Modern Python preserves insertion order for dictionaries, making it easy to rely on the order items were added. The chapter emphasizes how broadly useful and efficient dictionaries are, even in small programs.
After showing how to create and populate dictionaries (with literals and assignment), the chapter surveys everyday operations: measuring size with len, iterating via the dynamically updated keys, values, and items views, deleting entries with del, and merging with update. It demonstrates safe lookups with in and get (with defaults), how setdefault both retrieves and initializes a key, and when a shallow copy (copy) versus a deep copy (copy.deepcopy) is appropriate. A classic pattern—counting words—illustrates how get or setdefault simplifies frequency tallies and motivates related tools like collections.Counter.
The text explains what qualifies as a dictionary key: any immutable, hashable object, including numbers, strings, bytes, frozensets, and tuples that contain only hashable members. This enables powerful patterns such as using (row, column) tuples for sparse matrices and argument tuples for memoization caches that avoid recomputation. The chapter closes by reassuring readers that dictionaries are highly optimized in Python; choose them when they make code clearer, and only revisit alternatives if profiling shows a real performance concern.
Summary
Dictionaries are powerful data structures, used for many purposes even within Python itself.
Items in a dictionary are accessed by keys, not by their order in the dictionary.
Dictionary keys must be immutable, but any immutable object can be a dictionary key.
All dictionaries maintain items in the order in which they were added, but OrderDicts offers some extra features.
By using the keys as part of the data, dictionaries can be used for tasks like counting elements, caching values, or creating sparse matrices.
Using keys means accessing collections of data more efficiently and with less code than many other solutions.
FAQ
What is a dictionary in Python and how is it different from a list?A dictionary maps arbitrary keys to values using a hash table. Lists use integer indices; dictionaries use keys (numbers, strings, tuples, etc.). List elements are ordered by position; dictionary items aren’t inherently ordered relative to one another, though since Python 3.6 insertion order is preserved.Do dictionaries preserve insertion order? When would I use OrderedDict?Yes. Since Python 3.6, dictionaries preserve the order in which items are added. Use collections.OrderedDict when you need extra ordering features like move_to_end or reverse iteration methods.How do I create and update a dictionary?Create an empty dict with {} or a literal like {'red': 'rouge', 'blue': 'bleu'}. Assign or update with d[key] = value; assigning to a new key creates it automatically (unlike lists). Remove with del d[key].How do I iterate over a dictionary, and what do keys(), values(), and items() return?Use d.keys(), d.values(), and d.items() to get dynamic view objects you can iterate over. They reflect changes to the dictionary, support membership tests, and keys (and sometimes items) behave like sets. Wrap in list(...) if you need a list snapshot.How do I handle missing keys? What’s the difference between in, get, and setdefault?- Use 'key' in d to test existence.
- d.get('key', default) returns the value or default (default is None if omitted) without modifying the dict.
- d.setdefault('key', default) returns the value if present; otherwise it inserts default and returns it. For automatic defaults across many keys, consider collections.defaultdict.How do I combine or copy dictionaries?- Copy: d.copy() makes a shallow copy (use copy.deepcopy for deep copies if values are mutable objects).
- Merge: d.update(other) adds all key-value pairs from other, overwriting existing keys.What can I use as a dictionary key? What does “hashable” mean?Keys must be immutable and hashable (have a stable hash value). Valid examples: int, float, bool, complex, str, bytes, frozenset, and tuples that contain only hashable items. Lists, sets, dicts, and tuples containing mutable objects are not valid keys.How can I count word frequencies with a dictionary?Use the “accumulate with get” pattern: counts[word] = counts.get(word, 0) + 1. This keeps code simple and fast. For a ready-made tool, the standard library also provides collections.Counter.How do I represent a sparse matrix using a dictionary?Store only nonzero entries in a dict keyed by (row, col) tuples, for example {(0, 0): 3, (0, 3): 11}. Access with d.get((r, c), 0) to return 0 when the entry is absent.How can I use a dictionary as a cache (memoization), and are dictionaries efficient?Cache expensive results keyed by input arguments (often a tuple): if args in cache: return cache[args]; else compute, store, and return. Python dictionaries are highly optimized and used internally by the language, so this approach is both simple and fast for many workloads.
pro $24.99 per month
access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!