LevelJar Sign in

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

Start this module

Runs in your browser. Start straight away; create an account when you want your progress kept.

counting, then reporting
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

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

Start this module

Previous: Lists. Next: Functions. All modules are on the course page.