Dictionaries and sets
Look things up by key with dicts; track uniqueness with sets.
- Create and access dictionaries by key
- Iterate over keys and values
- Use a set for uniqueness and fast membership
When you need to look something up by a name rather than a position, you want a dictionary. When you need uniqueness or fast "is this in here?" checks, you want a set. These are the everyday structures from the fundamentals lesson, in Python form.
Dictionaries: key → value
A dict maps keys to values, written with {key: value}:
person = {"name": "Ada", "born": 1815}
person["name"] # "Ada" (look up by key)
person["role"] = "pioneer"# add a new key
person.get("age", 0) # 0 (default if key is missing — no error)
"name" in person # TrueLooking up by key is effectively instant no matter how big the dict gets — that's the whole reason to use one over scanning a list.
Iterating a dict
for key, value in person.items():
print(key, "->", value)person.keys() and person.values() give you each side alone.
Sets: unique items
A set holds unique values and answers membership fast:
seen = {1, 2, 2, 3} # {1, 2, 3} — duplicates collapse
3 in seen # True
seen.add(4)
unique = set([1, 1, 2]) # {1, 2} — dedupe a listUse a set to remove duplicates or to check membership against a large collection cheaply — exactly the "let the operations choose the structure" idea.
Rule of thumb: reaching for a list and then searching it with in a lot? A set
or dict is probably the right structure — instant lookups instead of scanning.
Where to go next
You now have Python's core data types. Next: errors and exceptions — handling things going wrong without crashing.