Python Dictionary Cheat Sheet: Methods and Examples
d[key] or d.get(key, default), add with d[key] = value or update(), remove with pop() or del, and loop with items().Dictionaries store data you look up by name, such as a student's name, age and city, and they keep insertion order. The tables below show each operation with the real result, grouped by what you are trying to do. For background see Python dictionaries and dictionary methods.
The key habit: use get() or in when a key might be missing, because d[key] raises KeyError.
Python dictionary creation and access cheat sheet
| Task | Code | Result |
|---|---|---|
| Create with braces | {"a": 1, "b": 2} | {'a': 1, 'b': 2} |
| Create with dict() | dict(a=1, b=2) | {'a': 1, 'b': 2} |
| Read a key | student["name"] | 'Asha' |
| Read with a default | student.get("grade", "n/a") | 'n/a' |
| Missing key raises | student["grade"] | KeyError: 'grade' |
| Key exists? | "age" in student | True |
| Number of keys | len(student) | 3 |
| Nested value | {"user": {"tags": ["x", "y"]}}["user"]["tags"][1] | 'y' |
| Keys from a list | dict.fromkeys(["a", "b"], 0) | {'a': 0, 'b': 0} |
| From two lists | dict(zip(["x", "y"], [1, 2])) | {'x': 1, 'y': 2} |
Python dictionary add, update and remove cheat sheet
| Task | Code | Result |
|---|---|---|
| Add or overwrite a key | student["grade"] = "A"; student | {'name': 'Asha', 'age': 20, 'city': 'Pune', 'grade': 'A'} |
| Update from another dict | student.update({"age": 21, "id": 7}); student | {'name': 'Asha', 'age': 21, 'city': 'Pune', 'id': 7} |
| Set only if missing | student.setdefault("grade", "B"); student | {'name': 'Asha', 'age': 20, 'city': 'Pune', 'grade': 'B'} |
| Pop a key (returns value) | student.pop("city") | 'Pune' |
| Pop with a default | student.pop("zip", None) | None |
| Remove the last item | student.popitem() | ('city', 'Pune') |
| Delete a key | del student["age"]; student | {'name': 'Asha', 'city': 'Pune'} |
| Clear all | student.clear(); student | {} |
| Copy | student.copy() == student | True |
| Merge into a new dict | student | {"age": 99} | {'name': 'Asha', 'age': 99, 'city': 'Pune'} |
| Merge in place | student |= {"zip": 1}; student | {'name': 'Asha', 'age': 20, 'city': 'Pune', 'zip': 1} |
Python dictionary views and looping cheat sheet
| Task | Code | Result |
|---|---|---|
| Keys | list(student.keys()) | ['name', 'age', 'city'] |
| Values | list(student.values()) | ['Asha', 20, 'Pune'] |
| Items as pairs | list(student.items()) | [('name', 'Asha'), ('age', 20), ('city', 'Pune')] |
| Loop over keys | [k for k in student] | ['name', 'age', 'city'] |
| Loop over key and value | [f"{k}={v}" for k, v in student.items()] | ['name=Asha', 'age=20', 'city=Pune'] |
| Sum of values | sum({"a": 3, "b": 4}.values()) | 7 |
| Find the key with the max value | max(marks, key=marks.get) | 'art' |
| Keys sorted | sorted(marks) | ['art', 'math', 'pe'] |
| Items sorted by value | sorted(marks.items(), key=lambda kv: kv[1]) | [('pe', 64), ('math', 72), ('art', 91)] |
| Sort by value, descending dict | dict(sorted(marks.items(), key=lambda kv: -kv[1])) | {'art': 91, 'math': 72, 'pe': 64} |
| Enumerate a dictionary | list(enumerate(marks, start=1)) | [(1, 'math'), (2, 'art'), (3, 'pe')] |
Python dictionary comprehension and transforming dicts
| Task | Code | Result |
|---|---|---|
| Dict comprehension | {n: n * n for n in range(4)} | {0: 0, 1: 1, 2: 4, 3: 9} |
| Filter by value | {k: v for k, v in marks.items() if v >= 70} | {'math': 72, 'art': 91} |
| Transform values | {k: v + 5 for k, v in marks.items()} | {'math': 77, 'art': 96, 'pe': 69} |
| Swap keys and values | {v: k for k, v in {"a": 1, "b": 2}.items()} | {1: 'a', 2: 'b'} |
| Count words | {w: "a b a".split().count(w) for w in set("a b a".split())} | {'a': 2, 'b': 1} |
| Group lengths | {len(w): w for w in ["hi", "yes"]} | {2: 'hi', 3: 'yes'} |
| Dict to list of tuples | list({"a": 1}.items()) | [('a', 1)] |
| Dict to JSON text | json.dumps({"a": 1, "ok": True}) | '{"a": 1, "ok": true}' |
| JSON text to dict | json.loads('{"a": [1, 2]}') | {'a': [1, 2]} |
| Counter for tallies | dict(Counter("hello")) | {'h': 1, 'e': 1, 'l': 2, 'o': 1} |
| defaultdict for grouping | dict(defaultdict(list, {"a": [1]})) | {'a': [1]} |
Python nested dictionaries and safe access cheat sheet
| Task | Code | Result |
|---|---|---|
| Read a nested key | data["user"]["name"] | 'Asha' |
| Safe nested read | data.get("team", {}).get("lead", "none") | 'none' |
| Add a nested key | data["user"]["role"] = "admin"; data["user"] | {'name': 'Asha', 'role': 'admin'} |
| List inside a dict | data["tags"][0] | 'a' |
| Append to a list value | data["tags"].append("c"); data["tags"] | ['a', 'b', 'c'] |
| Group items by key | g = {}; [g.setdefault(len(w), []).append(w) for w in ["a", "bb", "c"]]; g | {1: ['a', 'c'], 2: ['bb']} |
| Check for a key before reading | "team" in data | False |
| Shallow copy shares inner dicts | c = data.copy(); c["user"]["name"] = "Zed"; data["user"]["name"] | 'Zed' |
| Deep copy keeps them apart | c = copy.deepcopy(data); c["user"]["name"] = "Zed"; data["user"]["name"] | 'Asha' |
| Count keys of a nested dict | len(data["user"]) | 1 |
Python dictionary vs list vs set at a glance
| Task | Code | Result |
|---|---|---|
| Ordered by insertion? | list({"b": 1, "a": 2}) | ['b', 'a'] |
| Keys must be hashable | {(1, 2): "point"}[(1, 2)] | 'point' |
| List as a key fails | {[1]: 2} | TypeError: unhashable type: 'list' |
| Duplicate keys: last wins | {"a": 1, "a": 2} | {'a': 2} |
| Equality ignores order | {"a": 1, "b": 2} == {"b": 2, "a": 1} | True |
| Dict view as a set | sorted({"a": 1}.keys() | {"z"}) | ['a', 'z'] |
| Fast membership (keys) | "a" in {"a": 1} | True |
| Dictionary of lists | {"a": [1, 2]}["a"][-1] | 2 |
| Unpack into a function call | f(**{"a": 1, "b": 2}) | 3 |
| Convert keys to a set | sorted(set({"x": 1, "y": 2})) | ['x', 'y'] |
Examples you can run
Press Run, then edit the code and run it again.
Count words with a dictionary
Use get() with a default so the first time a word appears it starts at 0.
text = "red blue red green blue red"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts)Expected output{'red': 3, 'blue': 2, 'green': 1}
Sort a dictionary by value
Sort the items() with a key function and rebuild a dict.
marks = {"math": 72, "art": 91, "pe": 64}
ranked = dict(sorted(marks.items(), key=lambda kv: kv[1], reverse=True))
print(ranked)
print(next(iter(ranked)))Expected output{'art': 91, 'math': 72, 'pe': 64}
art
Python Dictionary Cheat Sheet: Methods and Examples: questions people ask
How do I add a key to a dictionary in Python?
Assign to it: d["new_key"] = value. If the key exists its value is replaced, otherwise a new pair is added.
How do I merge two dictionaries in Python?
Use d1 | d2 (Python 3.9+) to get a new dictionary, or d1.update(d2) to change d1 in place. When keys clash, the right-hand dictionary wins.
How do I avoid KeyError in a Python dictionary?
Use d.get(key, default), check key in d first, or use setdefault(). All three avoid raising KeyError for missing keys.
Keep learning
Step-by-step lessons:
Python DictionariesPython Dictionary MethodsPython Nested Data Structures
Related:
Python Cheat Sheet (Python 3.13 Quick Reference)Python List Cheat Sheet: Methods and ExamplesPython Dictionary get() MethodHow to Merge Two Dictionaries in PythonHow to Sort a Dictionary by Value in Python
More in core python:
Python Cheat Sheet (Python 3.13 Quick Reference)Python String Cheat Sheet: Methods and FormattingPython List Cheat Sheet: Methods and ExamplesPython Control Flow Cheat Sheet: if, for, while, matchPython Functions Cheat Sheet: def, args, lambda, scopePython OOP Cheat Sheet: Classes, Inheritance, Dunder MethodsPython Regex Cheat Sheet (re Module Quick Reference)Python File Handling Cheat Sheet: open, read, write, CSV, JSON See all →