Python Dictionary
A Python dictionary maps keys to values. Write it with braces and colons, {"pen1": "lion"}, or build it with dict(pen1="lion") or dict([(1, "lion")]). Access is by key rather than position: zoo[2] asks for the value stored under the key 2, not the third item. A missing key raises KeyError, and get(key, default) returns a fallback instead when absence is an ordinary case.
Keys must be hashable, with a stable hash and equal hashes for equal keys: built-in strings and numbers qualify, and a tuple qualifies only if every item does, while a list raises TypeError: unhashable type: 'list'. Values have no such restriction, and one key holds exactly one value, so assigning to an existing key replaces it. The dictionary itself is mutable, so zoo[4] = "crocodile" adds a pair and del zoo[4] removes it.
Since Python 3.7 a dictionary preserves the insertion order of its keys, so the same insertion history gives the same iteration order; unordered input can still vary across runs. Older material calling dictionaries “unordered” predates that guarantee. Preserved order is not sorted order: sort explicitly when you need alphabetical or numeric sequence. Iterating a dictionary yields keys; values() yields values and items() yields key-value pairs. The keys(), values(), and items() methods return live views. Adding or deleting keys during iteration may raise RuntimeError or miss entries; iterate a separate key list such as list(zoo) for those changes. Replacing an existing value without changing keys is different.
Grouping is the most common pattern: counts[key] = counts.get(key, 0) + 1 accumulates a total, and grouped.setdefault(key, []).append(row) collects rows under a key. Hash-based dictionary lookup is typically fast on average, although collisions can increase comparisons, which is why converting a list of rows into a dictionary keyed by the field you search on pays off when the same question is asked repeatedly.
References: Mapping types: dict, Dictionaries tutorial. See it in use in Python Collections and Comprehensions.
“`Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
