Python course / Foundations
Dictionaries, sets, tuples
Store data under names rather than positions, count and group it, and pick the collection that fits the question. A missing key brings a program down at the worst moment, so the lookups here are the ones that survive it.
- lookups
- counting
- grouping
- nested records
- sets
- tuples
- merging
- inverting
Runs in your browser. Start straight away; create an account when you want your progress kept.
sales = ["tea", "jam", "tea", "oats", "tea", "jam"]
counts = {}
for item in sales:
counts[item] = counts.get(item, 0) + 1
for name, count in sorted(counts.items(), key=lambda pair: -pair[1]):
print(f"{name}: {count}")
print("sold at all:", sorted(set(sales)))
tea: 3 jam: 2 oats: 1 sold at all: ['jam', 'oats', 'tea']
What you will learn
- Store values under names rather than positions.
- Read entries safely, whether or not the key is there.
- Tally how often each value appears.
- Hold a collection where each value appears once.
- Group a fixed number of values that belong together.
- Pick the shape that matches the question you will ask.
The lessons in this module
- Making a dictionary
- Looking up a value
- Adding and changing entries
- Removing entries
- Checking what is in a dictionary
- Looping over a dictionary
- Counting with a dictionary
- Grouping into lists
- Dictionaries inside dictionaries
- Order and sorting
- Merging dictionaries
- Changing a dictionary while looping
- Making a set
- Changing a set
- Comparing two sets
- Sets and order
- Tuples
- Tuples as keys
- Swapping and leftovers
- Copying a dictionary
- Building a dictionary from pairs
- Turning a dictionary around
- Ranking what you counted
- Choosing a collection
- Comparing two dictionaries
- Module review: room bookings
Ready when you are
Previous: Lists. Next: Functions. All modules are on the course page.