Part 3: Python Programming
Part 3: Python Programming — read through each chapter in order. Diagrams, tables and worked examples included.
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:
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:
Common dictionary operations
| Operation | Meaning | Example |
|---|---|---|
d[key] | Read a value | student["name"] |
d[key] = v | Add or update | student["grade"] = "A" |
del d[key] | Delete a pair | del student["age"] |
key in d | Test membership | "name" in student |
d.get(key, default) | Safe read | student.get("x", 0) |
d.keys() / d.values() | All keys / values | student.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:
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:
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:
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.