A Python dictionary is the collection type that maps keys to values. Unlike a list, where you look up items by their numeric position, or a set, where you only care whether an item exists, a dictionary lets you store a value under a name and retrieve that value later using the same name. The name is called a key, and the association between the key and its value is the defining feature of the dictionary. If lists are the workhorse for ordered data and sets are the tool for uniqueness, dictionaries are the backbone of data processing in Python. They appear everywhere: JSON responses from web APIs become dictionaries, configuration files parse into dictionaries, word counting produces dictionaries, and Python's own internal namespace, the mapping from variable names to their values, is implemented as a dictionary.
The article on Python collections explained introduced dictionaries as one of the four core collection types. This article goes deeper into how dictionaries work, why they are fast, what makes a valid key, and when dictionaries outperform every alternative. If you are coming from the earlier articles on lists and sets, you will notice that dictionaries combine properties from both: they are mutable like lists, they use hash-table internals like sets, and they offer the unique capability of retrieving a stored value by a known identifier in constant time.
How dictionaries work
A dictionary stores key-value pairs in a hash table, the same data structure that powers sets. When you insert a key-value pair, Python computes a hash of the key, uses that hash to determine a slot in the internal table, and stores both the key and the value at that slot. When you later look up the value by that key, Python hashes the key again, jumps directly to the same slot, and returns the value. No scanning, no searching, and no looping is required.
This hash-table design means that retrieving a value by its key takes the same amount of time whether the dictionary contains ten entries or ten million. The speed of a lookup depends only on the time it takes to hash the key and resolve any hash collisions, not on the total number of entries. This constant-time lookup is what makes dictionaries the right choice for any program that needs to associate identifiers with data and retrieve that data frequently.
scores = {"Alice": 92, "Bob": 85, "Charlie": 78}
scores["Bob"]The lookup scores["Bob"] does not scan through Alice and then Bob. It hashes the string "Bob", jumps to the relevant slot, and returns 92 in a single operation. This performance characteristic holds regardless of how many names and scores the dictionary contains.
What makes a valid key
Dictionary keys must be hashable, which in Python means they must be immutable and must implement the hash method and an equality comparison. The hash value of a key is used to locate the key in the hash table, and two keys that compare equal must have the same hash. If a key's hash value could change after insertion, Python would lose track of where the key-value pair is stored.
In practice, strings, integers, floats, booleans, and tuples of immutable elements are the most common key types. Lists, sets, and dictionaries themselves cannot be keys because they are mutable. A tuple can be a key only if every element inside it is also hashable. A tuple containing a list is not a valid key because the inner list is mutable and could change, altering the tuple's hash.
The immutability requirement is the same one that applies to set elements. Both data structures share the same hashing infrastructure, and both enforce the same constraints. If you need a mapping where the keys themselves are mutable collections, you will need a different approach, such as using a unique immutable identifier as the key and storing the mutable collection as the value.
Dictionaries in real programs
Dictionaries are not just another collection type; they are the format in which structured data flows through Python programs. When you call an external API and receive a JSON response, parsing that JSON produces a dictionary. When you read a configuration file in YAML or TOML, the parsed result is a dictionary. When you use keyword arguments in a function call, Python packs them into a dictionary before passing them to the function.
This ubiquity means that fluency with dictionaries translates directly into fluency with data processing in Python. Counting word frequencies in a text uses a dictionary where each word is a key and the count is the value. Grouping records by category uses a dictionary where each category is a key and the value is a list of records in that category. Caching the results of expensive function calls uses a dictionary where the function arguments are the key and the returned value is stored for reuse.
The article on accessing and updating dictionaries in Python covers the practical operations: retrieving values safely with the get method, adding and modifying entries, removing keys, and iterating over keys, values, and key-value pairs. Together, these two articles give you everything you need to use dictionaries effectively in any Python program.
Rune AI
Key Insights
- A dictionary maps unique, hashable keys to arbitrary values using curly braces or the dict() constructor.
- Lookups by key run in constant time, making dictionaries the fastest structure for key-based retrieval.
- Keys must be immutable; strings, numbers, and tuples are common choices.
- Dictionaries preserve insertion order as of Python 3.7.
- Use dicts for lookups, counting, grouping, caching, and anywhere you need to associate one value with another.
Frequently Asked Questions
What is a Python dictionary?
What can be a dictionary key?
Are Python dictionaries ordered?
Conclusion
Dictionaries are the most versatile and widely used collection type in Python. They power JSON parsing, configuration management, caching, counting, grouping, and virtually every program that needs to associate one piece of data with another. Mastering dictionaries is not optional for any Python programmer.
More in this topic
Define and Call Python Functions
Learn the exact syntax for defining and calling Python functions with the def keyword, including naming rules, the function body, and how the call stack works.
Python Function Parameters and Arguments
Learn the difference between parameters and arguments, how to pass values by position and by keyword, and the rules for default parameter values.
Python Functions Explained
Learn what Python functions are, why they matter for organizing code, and how they form the foundation of non-trivial programs.