Also known as: dict, hash map
A dictionary (dict) is Python's built-in mapping type, storing key–value pairs with O(1) average-case lookup, insertion, and deletion. Dictionaries are created with braces ({'a': 1, 'b': 2}) or the dict() constructor. Keys must be hashable (typically strings, numbers, or tuples); values can be any object. Since Python 3.7, dictionaries preserve insertion order as a language guarantee.
Common operations include d[key] (lookup, raises KeyError if missing), d.get(key, default) (safe lookup), d[key] = val (insert or update), del d[key] (delete), and key in d (membership test). The methods .keys(), .values(), and .items() return dynamic views. Dictionary comprehensions ({k: v for k, v in pairs}) create dictionaries concisely.
Dictionaries are arguably the most important data structure in Python. They underpin the implementation of namespaces (module globals, instance attributes, and local variables in some contexts), keyword arguments, class definitions, and the json module. The collections module provides specialised dictionary variants: defaultdict (automatic default values), OrderedDict (comparison semantics that care about order), and Counter (tallying hashable objects).
Related terms: Mutable, Set, Comprehension
Discussed in:
- Chapter 6: Data Structures — Dictionaries