9. Dictionaries & Sets

Dictionaries & Sets

Lists store items by position. Sometimes you would rather look things up by a meaningful label, like a phone book that maps names to numbers. Python's dictionary does exactly that, and the set stores a collection of unique items.

Creating a dictionary

A dictionary holds key-value pairs. Write it with curly braces, each key followed by a colon and its value. Keys are usually strings or numbers and must be unique; values can be anything:

PYTHON
student = {"name": "Ada", "age": 25, "passed": True}
print(student["name"])
print(student["age"])
▸ OUTPUT
Ada
25

You access a value by putting its key in square brackets. Asking for a key that does not exist raises a KeyError; to avoid that, use .get(), which returns None (or a default you supply) when the key is missing.

Adding, updating, and deleting

Dictionaries are mutable. Assigning to a new key adds it; assigning to an existing key updates it; del removes a pair:

PYTHON
student["grade"] = "A"
student["age"] = 26
del student["passed"]
print(student)
print(student.get("email", "no email"))
▸ OUTPUT
{'name': 'Ada', 'age': 26, 'grade': 'A'}
no email

Common dictionary operations

OperationMeaningExample
d[key]Read a valuestudent["name"]
d[key] = vAdd or updatestudent["grade"] = "A"
del d[key]Delete a pairdel student["age"]
key in dTest membership"name" in student
d.get(key, default)Safe readstudent.get("x", 0)
d.keys() / d.values()All keys / valuesstudent.keys()

Iterating over a dictionary

Looping over a dictionary gives you the keys. The .items() method is the usual way to get both the key and value each pass:

PYTHON
prices = {"apple": 0.5, "bread": 1.2, "milk": 0.9}
for item, cost in prices.items():
    print(f"{item} costs ${cost:.2f}")
▸ OUTPUT
apple costs $0.50
bread costs $1.20
milk costs $0.90

Sets and uniqueness

A set is an unordered collection that automatically removes duplicates. Create one with curly braces (but with no colons) or the set() function. Sets are great for membership tests and for removing repeats from a list:

PYTHON
numbers = [1, 2, 2, 3, 3, 3]
unique = set(numbers)
print(unique)
print(3 in unique)
▸ OUTPUT
{1, 2, 3}
True

Note that a set has no indexes because it has no order, so you cannot write unique[0].

Set operations

Sets support the mathematical operations of union, intersection, and difference. These answer questions like "what do two groups share?" quickly and clearly:

PYTHON
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b)
print(a & b)
print(a - b)
▸ OUTPUT
{1, 2, 3, 4, 5, 6}
{3, 4}
{1, 2}

The | operator gives the union (everything in either set), & gives the intersection (items in both), and - gives the difference (items in the first but not the second).

Dictionaries and sets round out Python's core data structures. Reach for a dictionary whenever you want to look data up by name, and for a set whenever uniqueness or fast membership checks matter. Practice by counting how many times each letter appears in a word using a dictionary.