Cheat sheetCore Python

Python Dictionary Cheat Sheet: Methods and Examples

Short answer
A Python dictionary maps unique keys to values: read with 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

Assume `student = {"name": "Asha", "age": 20, "city": "Pune"}`.
TaskCodeResult
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 keystudent["name"]'Asha'
Read with a defaultstudent.get("grade", "n/a")'n/a'
Missing key raisesstudent["grade"]KeyError: 'grade'
Key exists?"age" in studentTrue
Number of keyslen(student)3
Nested value{"user": {"tags": ["x", "y"]}}["user"]["tags"][1]'y'
Keys from a listdict.fromkeys(["a", "b"], 0){'a': 0, 'b': 0}
From two listsdict(zip(["x", "y"], [1, 2])){'x': 1, 'y': 2}

Python dictionary add, update and remove cheat sheet

Each row starts from the same `student` dictionary.
TaskCodeResult
Add or overwrite a keystudent["grade"] = "A"; student{'name': 'Asha', 'age': 20, 'city': 'Pune', 'grade': 'A'}
Update from another dictstudent.update({"age": 21, "id": 7}); student{'name': 'Asha', 'age': 21, 'city': 'Pune', 'id': 7}
Set only if missingstudent.setdefault("grade", "B"); student{'name': 'Asha', 'age': 20, 'city': 'Pune', 'grade': 'B'}
Pop a key (returns value)student.pop("city")'Pune'
Pop with a defaultstudent.pop("zip", None)None
Remove the last itemstudent.popitem()('city', 'Pune')
Delete a keydel student["age"]; student{'name': 'Asha', 'city': 'Pune'}
Clear allstudent.clear(); student{}
Copystudent.copy() == studentTrue
Merge into a new dictstudent | {"age": 99}{'name': 'Asha', 'age': 99, 'city': 'Pune'}
Merge in placestudent |= {"zip": 1}; student{'name': 'Asha', 'age': 20, 'city': 'Pune', 'zip': 1}

Python dictionary views and looping cheat sheet

Also assume `marks = {"math": 72, "art": 91, "pe": 64}`. Dictionaries keep insertion order.
TaskCodeResult
Keyslist(student.keys())['name', 'age', 'city']
Valueslist(student.values())['Asha', 20, 'Pune']
Items as pairslist(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 valuessum({"a": 3, "b": 4}.values())7
Find the key with the max valuemax(marks, key=marks.get)'art'
Keys sortedsorted(marks)['art', 'math', 'pe']
Items sorted by valuesorted(marks.items(), key=lambda kv: kv[1])[('pe', 64), ('math', 72), ('art', 91)]
Sort by value, descending dictdict(sorted(marks.items(), key=lambda kv: -kv[1])){'art': 91, 'math': 72, 'pe': 64}
Enumerate a dictionarylist(enumerate(marks, start=1))[(1, 'math'), (2, 'art'), (3, 'pe')]

Python dictionary comprehension and transforming dicts

Assume `import json` and `from collections import Counter, defaultdict`.
TaskCodeResult
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 tupleslist({"a": 1}.items())[('a', 1)]
Dict to JSON textjson.dumps({"a": 1, "ok": True})'{"a": 1, "ok": true}'
JSON text to dictjson.loads('{"a": [1, 2]}'){'a': [1, 2]}
Counter for talliesdict(Counter("hello")){'h': 1, 'e': 1, 'l': 2, 'o': 1}
defaultdict for groupingdict(defaultdict(list, {"a": [1]})){'a': [1]}

Python nested dictionaries and safe access cheat sheet

Assume `data = {"user": {"name": "Asha"}, "tags": ["a", "b"]}` and `import copy`.
TaskCodeResult
Read a nested keydata["user"]["name"]'Asha'
Safe nested readdata.get("team", {}).get("lead", "none")'none'
Add a nested keydata["user"]["role"] = "admin"; data["user"]{'name': 'Asha', 'role': 'admin'}
List inside a dictdata["tags"][0]'a'
Append to a list valuedata["tags"].append("c"); data["tags"]['a', 'b', 'c']
Group items by keyg = {}; [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 dataFalse
Shallow copy shares inner dictsc = data.copy(); c["user"]["name"] = "Zed"; data["user"]["name"]'Zed'
Deep copy keeps them apartc = copy.deepcopy(data); c["user"]["name"] = "Zed"; data["user"]["name"]'Asha'
Count keys of a nested dictlen(data["user"])1

Python dictionary vs list vs set at a glance

TaskCodeResult
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 setsorted({"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 callf(**{"a": 1, "b": 2})3
Convert keys to a setsorted(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.

Count words with a dictionary
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.

Sort a dictionary by value
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 →