Python dict examples show how to build fast lookup tables in everyday scripts. These structures store key value pairs that map directly to real world objects and JSON records.
Use cases include configuration handling, caching results, and transforming API responses. The following sections walk through practical patterns, common pitfalls, and best practices.
| Key | Type | Mutable | Typical Use |
|---|---|---|---|
| "name" | str | Yes | Labeling objects |
| 1 | int | Yes | Numeric keys |
| ("lat", "lon") | tuple | Yes | Composite keys |
| None | NoneType | Yes | Optional flags |
| frozenset({1, 2}) | frozenset | No | Hashable keys |
Creating basic dict structures
Start with curly braces or the dict constructor. Empty dicts begin as d = {} and grow via assignment.
Literal syntax patterns
Literal syntax keeps code concise and readable. Examples include {"city": "Berlin", "year": 2023} and {}.
Constructor with iterable
The dict constructor accepts pairs, allowing you to convert lists of tuples into mappings cleanly.
Reading and updating values
Access items with square brackets and assign new values in place. Missing keys raise KeyError unless handled.
Safe get with default
Use .get("key", default) to avoid exceptions and supply fallback values when a key is absent.
Updating multiple fields
Method .update() merges another mapping or iterable of key value pairs, overwriting existing entries efficiently.
Iterating and transforming dicts
Loops over .items() provide both keys and values, while .keys() and .values() focus on one dimension each.
Building new dicts
Dict comprehensions let you filter and remap entries in a single line, improving clarity and performance.
Order and insertion behavior
Since Python 3.7, standard dict preserves insertion order, which aligns with JSON expectations and simplifies debugging.
Nested and complex values
Store lists, other dicts, or custom objects as values to model hierarchical data structures naturally.
Handling missing branches
Use collections.defaultdict or .setdefault to create sub dictionaries on the fly without repeated checks.
Flattening for analysis
Recursive traversal helps flatten nested mappings into tabular formats for reporting or export.
Best practices with Python dict
- Prefer .get or setdefault for safe access in production code.
- Use .update for bulk merges instead of repeated single assignments.
- Choose immutable keys like strings, numbers, or frozensets to ensure hash stability.
- Apply dict comprehensions for clarity when filtering or transforming entries.
- Document nested structures so readers understand expected shapes and types.
FAQ
Reader questions
Can dict keys be lists in Python examples?
No, keys must be hashable; lists are unhashable, so use tuples or strings instead.
What happens if I assign to a missing key directly?
Python creates the key automatically with the assigned value, expanding the mapping.
How does .get differ from direct key access in examples?
.get returns None or a provided default, while direct access raises KeyError for missing keys.
Why does my dict iteration order differ from insertion order?
This can occur when deletions or updates reorganize internal storage; rely on language guarantees from Python 3.7 onward.