← All cheat sheets

Python dictionaries and sets cheat sheet 🗂️

Keys and values, get, items, counting things, nested data and sets. Every snippet runs in your browser, and the page prints on one sheet.

Make and read

ages = {"Ada": 36, "Linus": 54}
print(ages["Ada"])
print(ages.get("Bob"))
print(ages.get("Bob", 0))

[] crashes on a missing key; get() returns None or your default.

Add, change, remove

stock = {"apples": 5}
stock["pears"] = 3
stock["apples"] += 2
del stock["pears"]
print(stock)
print(stock.pop("apples"), stock)

Assigning to a key adds it or replaces its value.

Loop

prices = {"tea": 1.80, "cake": 2.50}
for item in prices:
    print(item)
for item, price in prices.items():
    print(f"{item}: £{price:.2f}")

Looping a dict gives keys. .items() gives key and value pairs.

Count things

words = "the cat and the hat and the bat".split()
counts = {}
for w in words:
    counts[w] = counts.get(w, 0) + 1
print(counts)
print(max(counts, key=counts.get))

The get(key, 0) + 1 pattern counts anything.

Sort by value

scores = {"Ava": 7, "Ben": 12, "Cal": 9}
for name, s in sorted(scores.items(), key=lambda kv: kv[1], reverse=True):
    print(name, s)

Dictionaries keep insertion order; sorted() with a key reorders them for printing.

Nested data

team = {"name": "Owls", "players": [{"name": "Ava", "goals": 3}, {"name": "Ben", "goals": 1}]}
for p in team["players"]:
    print(p["name"], p["goals"])
print(sum(p["goals"] for p in team["players"]))

This is the shape most JSON data comes in.

Sets

a = {"red", "green", "blue"}
b = {"blue", "yellow"}
print(sorted(a | b))
print(a & b)
print(sorted(a - b))
print(len(set([1, 1, 2, 3, 3])))

Sets hold each item once. | is union, & is shared, - is difference.

Start the free lessons More cheat sheets