Python dictionaries are mutable mappings that associate unique keys with values. They are a natural fit for configuration, structured records, caches, lookup tables, and JSON-like application data.
Create a Dictionary
Use a literal:
person = {
"name": "Alice",
"age": 30,
"city": "New York",
}Or use dict():
person = dict(name="Alice", age=30, city="New York")Since Python 3.7, normal dictionaries preserve insertion order as part of the language specification. They are still mappings rather than index-based sequences.
Access Values
Direct indexing is appropriate when the key is required:
name = person["name"]A missing key raises KeyError.
Use get() when the key is optional:
age = person.get("age")
job = person.get("job", "Not Specified")Add and Update Entries
person["email"] = "alice@example.com"
person["age"] = 31Update several values at once:
person.update({"age": 32, "city": "Boston"})On Python 3.9+, dictionary union provides another option:
updated = person | {"age": 32, "city": "Boston"}| creates a new dictionary; |= mutates the left-hand dictionary.
Remove Entries
Delete a known key:
del person["city"]Remove a key while retrieving its value:
age = person.pop("age")Provide a fallback when the key might be absent:
nickname = person.pop("nickname", None)Remove all entries:
person.clear()Check for Keys
if "name" in person:
print(person["name"])Membership tests check keys, not values.
Iterate Through a Dictionary
Keys:
for key in person:
print(key)Values:
for value in person.values():
print(value)Keys and values together:
for key, value in person.items():
print(key, value)Dictionary Comprehensions
squares = {number: number * number for number in range(1, 6)}Filter while building a mapping:
even_squares = {
number: number * number
for number in range(10)
if number % 2 == 0
}What Can Be a Key?
Dictionary keys must be hashable. Strings, integers, and tuples containing only hashable values are common keys:
locations = {
(40.7128, -74.0060): "New York",
}Lists and ordinary dictionaries are mutable and therefore cannot be dictionary keys.
Nested Dictionaries
users = {
"alice": {"age": 30, "active": True},
"bob": {"age": 25, "active": False},
}
print(users["alice"]["active"])For deeply nested or strongly structured data, consider dataclasses, TypedDict, validation models, or domain classes when they make the expected schema clearer.
setdefault() and defaultdict
setdefault() can initialize a missing value while returning the stored value:
groups = {}
groups.setdefault("admin", []).append("Alice")For repeated default construction, collections.defaultdict may be clearer:
from collections import defaultdict
groups = defaultdict(list)
groups["admin"].append("Alice")Conclusion
Dictionaries are Python’s general-purpose key-value mapping. Use direct indexing for required keys, get() for optional values, .items() for iteration, and comprehensions for concise construction. Remember that dictionaries preserve insertion order but are organized around keys rather than numeric positions.