All lessons

Functions & collections · step 17 of 22

Dictionaries & sets

11 minLook values up by name, and keep only the unique ones.

Look things up by name

A dictionary stores labelled values: keys and values. Instead of a position, you ask for a name.

student = {"name": "Ada", "age": 36}
print(student["name"])          # Ada
student["city"] = "London"      # add a new pair
print(student.get("email"))     # None — no crash when the key is missing

Use student["key"] when the key must exist, and .get("key") when it might not.

Looping through a dictionary

prices = {"apple": 0.5, "bread": 3.2}
for item, price in prices.items():
    print(f"{item} costs {price}")

.keys(), .values() and .items() are the three you will reach for. Dicts remember insertion order in modern Python, but treat them as lookups rather than sequences.

Sets: unique values

A set throws duplicates away and answers "is this in here?" very quickly.

votes = ["a", "b", "a", "c", "b"]
print(set(votes))         # {'a', 'b', 'c'}
print(len(set(votes)))    # 3

Remember this

  • Dictionaries map keys to values
  • Look up with d["key"], or d.get("key") to avoid crashes
  • A set keeps only unique values

Quick quiz

Three questions. 3 correct answers and you have the idea — you can retry as often as you like.

  1. 1. How do you read the value stored under the key 'name'?

  2. 2. What does set([1, 1, 2, 3, 3]) contain?

  3. 3. What does prices.items() give you?

Answer all three to check them.

Now write it yourself

0/3 passed
1

Practice 1

Build a dictionary called `prices` with apple at 0.5 and bread at 3.2, then print the price of bread.

practice_1.py
2

Practice 2

The dictionary `scores` is ready. Print one line per student in the format `Ada scored 92`.

practice_2.py

Given for you

scores = {"Ada": 92, "Grace": 88}
3

Practice 3

The list `votes` is ready. Print how many unique votes there are.

practice_3.py

Given for you

votes = ["a", "b", "a", "c", "b"]

Finish with two of three quiz answers correct and every exercise passing, and this lesson is marked complete.