Python Dictionaries: Key-Value Maps
A dictionary is an ordered (as of Python 3.7+), mutable collection of key-value pairs. Keys must be immutable (string, number, or tuple), but values can be anything! It is one of Python's most powerful data structures for structured data.
python
Creating Dicts
python
Accessing and Modifying
| Method | Action | Example |
|---|---|---|
| dict[key] | Access (raises ERROR if missing) | user["id"] |
| .get(key, default) | Access (safe, returns None if missing) | user.get("age", 25) |
| .update(other) | Combine with another dict | user.update({"age": 25}) |
| .pop(key) | Remove and return item | val = user.pop("id") |
| del dict[key] | Remove key | del user["tags"] |
python
Iteration: Keys, Values, Items
python
Dict Comprehensions
Similar to list comprehensions, but for generating dictionaries!
python
Advanced Dict Utilities: collections
1. defaultdict
Avoids
KeyError by providing a default value for new keys.python
2. OrderedDict
Though regular dicts now preserve order,
OrderedDict provides additional sub-classing and re-ordering capabilities.Merging Dictionaries (Python 3.9+)
Use the union operators to merge dictionaries easily!
python
Warning: If keys overlap, the value from the right-hand dictionary wins!
Summary
| Feature | Method / Syntax |
|---|---|
| Safe Access | .get(key, default) |
| Remove | .pop(key), del d[key] |
| Iterate | .items(), .keys(), .values() |
| Construct | {k:v for ...} |
| Merge | `d1 |
| Default | defaultdict(factory) |
| Best For | Structured data, JSON-like maps |