Python: Dictionaries
Learn to work with key-value data in Python. Dictionaries are one of the most powerful built-in structures, and understanding their methods and variants unlocks cleaner, faster code.
Creating Dictionaries
A dictionary is an unordered (insertion-ordered since Python 3.7) collection of key-value pairs. Each unique key maps to a single value. Dictionaries are defined with curly braces and colons separating each key from its value.
Key Rules
Not everything can be a dictionary key.
- Keys must be immutable: strings, numbers, and tuples are valid keys
- Lists and other dicts cannot be keys (they are mutable)
- Values can be any Python object, including lists, dicts, or functions
- Duplicate keys are not allowed; the last one assigned wins
Creating Dictionaries
PythonThree equivalent ways to build a dictionary.
Accessing and Modifying Values
You access a value by placing its key inside square brackets. If the key does not exist, Python raises aKeyError. To avoid this, use the get() method, which returns None(or a default you specify) if the key is absent.
Safe Access and Modification
PythonReading and changing values by key.
Adding and Removing Items
Python gives you multiple ways to remove entries from a dictionary. Choose the right tool depending on whether you need the removed value back, want to remove the last item, or need to wipe everything at once.
Deletion Techniques
Pythondel, pop, and popitem in practice.
Core Methods: keys, values, and items
Three methods give you views into the dictionary's contents. These views are not static copies; they reflect any changes made to the dictionary. Iterating over them is the standard way to process dictionary data.
Dictionary Views
PythonWorking with keys, values, and pairs together.
Methods: update, setdefault, and copy
update() merges another dictionary (or key-value pairs) into the current one.setdefault() is a pattern for initializing a key only if it does not already exist.copy()returns a shallow copy of the dictionary.
Merging and Safe-Setting
PythonCombining dicts and avoiding key collisions.
Iterating through Dictionaries
Iterating directly over a dictionary loops through its keys. Use .items()when you need both the key and the value at the same time, which is by far the most common pattern.
Looping Patterns
PythonThree ways to iterate over dictionary data.
Nested Dictionaries
A dictionary can contain other dictionaries as values. This is a natural way to represent structured data such as a user record with an embedded address.
Hierarchical Data
PythonStoring records within records.
Dictionary Comprehensions
Just like list comprehensions, dictionary comprehensions let you build a dictionary in a single readable expression. The syntax uses curly braces with an expression for both the key and the value.
Building on the Fly
PythonTransforming data into key-value pairs.
Special Dictionaries from collections
The collections module provides dictionary subclasses that solve very specific problems. These are worth knowing because they save you from writing boilerplate code for common patterns.
When to Use Each
Pick the right tool for the job.
- defaultdict: when you need a dict that auto-initializes missing keys (e.g., grouping items)
- OrderedDict: when the order of insertion is semantically meaningful (less common since Python 3.7+)
- Counter: when you need to count occurrences of items in a sequence
- ChainMap: when you want to combine multiple dicts into a single, logical view
collections in Action
PythonFour specialized dictionary types.
Merging Dictionaries with | (Python 3.9+)
Python 3.9 introduced the |operator for merging two dictionaries into a new one, and the|= operator for in-place merging. This is cleaner than using update()when you want to keep the original intact.
The Merge Operator (Python 3.9+)
PythonClean one-liner dictionary merging.
Quiz - Test Your Knowledge
Test what you have learned about Python dictionaries. Pay close attention to the difference between access patterns, the behaviour of each removal method, and when to reach for the collections module.
Knowledge Check
1. Which method safely retrieves a value from a dictionary without raising a KeyError?
2. What does dict.popitem() do?
3. In Python 3.9+, what does d1 | d2 produce?
4. What does collections.Counter(["a", "b", "a", "c", "a"]) return?
5. What is the purpose of setdefault()?
6. Which collection preserves insertion order and retains its position when a key is re-inserted?
7. How do you create a dictionary comprehension that maps numbers to their squares?
8. What is the main advantage of defaultdict over a regular dict?