The essentials
Quick reference
One focused task per row. Jump to the related section for complete, working examples.
| Use | Syntax | Examples |
|---|---|---|
| Create a dictionary | user = {"name": "Ada", "role": "engineer"} | View examples |
| Create from keywords | user = dict(name="Ada", role="engineer") | View examples |
| Read a required key | name = user["name"] | View examples |
| Read an optional key | timezone = user.get("timezone", "UTC") | View examples |
| Check for a key | if "role" in user: print(user["role"]) | View examples |
| Set one value | user["active"] = True | View examples |
| Update several values | user.update({"role": "lead", "active": True}) | View examples |
| Create a merged dictionary | combined = defaults | overrides | View examples |
| Remove and return a value | role = user.pop("role", None) | View examples |
| Delete a required key | del user["active"] | View examples |
| Iterate over pairs | for key, value in user.items(): print(key, value) | View examples |
| Iterate over keys | for key in user: print(key) | View examples |
| Build with a comprehension | squares = {number: number ** 2 for number in range(4)} | View examples |
| Initialize a missing key | tags = groups.setdefault("python", []) | View examples |
Dictionaries map unique, hashable keys to values. Choose direct indexing when a key must exist, use get for optional keys, and iterate through views when you need keys, values, or both.
Step by step
Detailed examples
Create dictionaries from values
A dictionary literal works with any hashable keys and makes the mapping visible. The dict constructor is concise when every key is a valid Python identifier and should become a string.
user = {"name": "Ada", "role": "engineer"}
settings = dict(theme="dark", compact=True)
print(user)
print(settings) {'name': 'Ada', 'role': 'engineer'}
{'theme': 'dark', 'compact': True}Note: The keyword form cannot directly create keys containing spaces, hyphens, or other non-identifier characters.
Choose between indexing, get, and membership
Index a dictionary when a missing key represents an error. Use get when absence is expected, and use membership when later logic needs to distinguish a missing key from a key whose value is None.
user = {"name": "Ada", "role": "engineer"}
name = user["name"]
timezone = user.get("timezone", "UTC")
print(name)
print(timezone)
if "role" in user:
print(user["role"]) Ada
UTC
engineerAdd, update, and merge values
Assignment and update mutate the existing dictionary. The merge operator creates a new dictionary, which is useful when the original mappings should remain unchanged. Later values replace earlier values for duplicate keys.
user = {"name": "Ada", "role": "engineer"}
user["active"] = True
user.update({"role": "lead", "location": "London"})
defaults = {"theme": "light", "compact": False}
overrides = {"theme": "dark"}
combined = defaults | overrides
print(user)
print(combined) {'name': 'Ada', 'role': 'lead', 'active': True, 'location': 'London'}
{'theme': 'dark', 'compact': False}Note: The dictionary merge operator requires Python 3.9 or newer.
Remove keys deliberately
Use pop when the removed value is needed or when a fallback should make a missing key harmless. Use del when the key must exist and only removal matters.
user = {"name": "Ada", "role": "engineer", "active": True}
role = user.pop("role", None)
del user["active"]
print(role)
print(user) engineer
{'name': 'Ada'}Iterate over keys and values
Iteration over a dictionary yields keys. Calling items returns a dynamic view of key-value pairs. Dictionaries preserve insertion order, but sorting should be explicit when output requires another order.
user = {"name": "Ada", "role": "engineer"}
for key in user:
print(key)
for key, value in user.items():
print(f"{key}: {value}") name
role
name: Ada
role: engineerNote: Do not add or remove dictionary keys while iterating over its live views; iterate over a list copy when structural changes are required.
Build and initialize dictionary values
A dictionary comprehension creates a new mapping from an iterable. Setdefault is useful for initializing mutable grouping values, but a regular conditional or collections.defaultdict can be clearer when initialization logic grows.
squares = {number: number ** 2 for number in range(4)}
groups = {}
tags = groups.setdefault("python", [])
tags.append("collections")
print(squares)
print(groups) {0: 0, 1: 1, 2: 4, 3: 9}
{'python': ['collections']}Local code tester
Try dictionary operations
Edit and run the Python locally to practice reading, updating, grouping, and iterating over a dictionary.
Press Run to load Python locally.
Sources and further reading
References
Authoritative documentation used to verify and expand this cheat sheet.
Help us improve
Found a typo or missing example?
Tell us what would make this cheat sheet clearer, more complete, or more useful.



