A dictionary, or dict, stores key–value pairs and lets programs retrieve values through keys rather than integer indexes. Keys are unique and hashable; values can be any objects, including other dictionaries. section 5.0 section 5.20
Use dictionaries when the data has meaningful associations or must grow while a program runs:
- Represent small databases or records, such as configuration options, user preferences, website details, menu items, or user IDs. section 5.0 section 5.4
- Accumulate values by key, such as rainfall totals, error counts, response-code data, or word statistics. section 5.8 section 5.11
- Store related data together, pass it to functions as one value, and build nested structures such as dictionaries of dictionaries. section 5.0 section 6.23
- Use keys to dispatch behavior by mapping strings to functions, rather than building a long conditional chain. section 7.7
Dictionary lookup uses hashing: a hash function supports unique keys and fast searches, contrasted with the linear search of sequences. The key must be hashable, while the associated value has no such restriction. section 5.1 section 5.20
Prefer membership tests for existence checks and dict.get when a missing key should produce a default instead of an error. Iterate directly over keys, or use key views with set operations. section 5.5 section 5.13
Accumulating values safely
rainfall[city_name] = rainfall.get(city_name, 0) + mm_rain This handles both a first observation and later observations for the same city. Validate numeric input before updating the dictionary; otherwise, string input can cause incorrect accumulation. section 5.9
A dictionary dispatch table
operations = {'+': add, '-': sub, '*': mul} return operations[op](first, second) The keys select functions, and the retrieved function is then called with the operands. section 7.7
all_keys = first.keys() | second.keys()
Inspect the compact set-union expression used to collect every distinct key from two dictionaries before comparing them. section 5.13









































