Dictionaries in Python

From the Python cheat sheet ยท Data Structures ยท verified Jul 2026

Dictionaries

Key-value mappings with fast lookups.

python
d = {"name": "Alice", "age": 30}
d["name"]              # "Alice"
d.get("email", "N/A")  # "N/A" (default)
d["email"] = "a@b.com" # Add/update
d.keys()               # dict_keys
d.values()             # dict_values
d.items()              # key-value pairs
del d["age"]           # Remove key
๐Ÿ’ก Use .get(key, default) to avoid KeyError on missing keys
โšก The | merge operator (3.9+) creates a new dict โ€” |= merges in place
๐Ÿ“Œ Use .items() to iterate over key-value pairs, not just keys
๐ŸŸข .setdefault() gets a value or inserts a default โ€” great for counting/grouping
dictionariesdata-structures

More Python tasks

Back to the full Python cheat sheet