Look things up by name instead of position with dictionaries, and keep unique items with sets. Learn the operations that make both fast and useful.
By the end of today you can
- Create dictionaries and read values by key
- Add, update and delete entries, and loop over keys and values
- Use get() to avoid KeyError
- Remove duplicates and compare groups with sets
- Know why keys and set items must be hashable
Lists find items by position. But often you want to look something up by name: a word's definition, a product's price, a user's email. That's a dictionary. And when you only care whether something is present, with no duplicates, you want a set.
Dictionaries: keys and values
A dictionary stores key → value pairs inside curly braces. Each key appears once and points to one value.
Missing keys: get()
Adding, updating and deleting
Looping over a dictionary
Counting with a dictionary
A classic use: count how often each thing appears.
Sets: unique items
A set is an unordered collection with no duplicates. Use it to remove duplicates or to test membership quickly.
Set operations
Sets shine when you compare groups:
| Operator | Name | Result |
|---|---|---|
a | b | Union | Items in either set |
a & b | Intersection | Items in both sets |
a - b | Difference | Items in a but not b |
a ^ b | Symmetric difference | Items in exactly one set |
Why keys must be hashable
Dictionaries and sets find items almost instantly by turning each key into a number called a hash. That only works if the key can never change, so keys and set items must be immutable: strings, numbers and tuples work, but lists, dicts and sets don't.
Recap
- A dict maps unique keys to values; use
d[key], ord.get(key, default)to avoidKeyError. - Add or update with
d[key] = value; loop with.items()for keys and values together. - A set holds unique items; use
|,&,-and^to compare groups. - Keys and set items must be hashable (immutable): strings, numbers, tuples.
Knowledge check
Test what you learned
5 questions · pick an answer to see if you're right
- 1
user = {"name": "Ada", "age": 36}. What does user["name"] return?
- 2
What happens with user["email"] if the dictionary has no "email" key?
- 3
What is set([3, 1, 3, 2, 1])?
- 4
a = {1, 2, 3} and b = {2, 3, 4}. What is a & b?
- 5
Which of these can be a dictionary key?
Finished today's lesson?