Module 8 · Python for Beginners
Dictionaries and Sets
Store values by name with dictionaries: create, read safely with get, add, change and remove, loop through keys, values and items, count things, and nest data. Then sets for unique values.
About 30 minutes
Open in ColabEvery example as a notebook you can run, edit and save to your Google Drive.
What a dictionary is
A list finds values by position: scores[0]. That's awkward when the values have names. Is the student's department student[1] or student[2]? A dictionary stores key: value pairs, so you look values up by name, like a word in a real dictionary.
Write it with curly brackets, a colon between each key and its value, and commas between pairs:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
{'name': 'Musa', 'department': 'Accounting', 'level': 300, 'cgpa': 3.9}- Keys are usually text, and each key appears only once.
- Values can be anything: text, numbers, lists, even other dictionaries.
- Dictionaries keep the order you added things in.
Reading values
Put the key in square brackets:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
Musa
300If the key doesn't exist, that's an error. get() is the safe way: it returns None, or a default you choose, instead:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
3.9
None
Not assignedCheck whether a key exists with in:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
True
FalseAdding, changing and removing
Assigning to a key adds it if it's new and changes it if it exists:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
{'name': 'Musa', 'department': 'Accounting', 'level': 400, 'cgpa': 3.9, 'hall': 'Jaja'}| You want to... | Write |
|---|---|
| add or change one | d["key"] = value |
| add or change several | d.update({"a": 1, "b": 2}) |
| remove one and get its value | value = d.pop("key") |
| remove one | del d["key"] |
| empty it | d.clear() |
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
{'name': 'Musa', 'department': 'Accounting', 'level': 400, 'cgpa': 4.0, 'hall': 'Jaja'}
Removed: 0803 000 0000Looping through a dictionary
Three methods give you the parts:
| Method | Gives |
|---|---|
.keys() | the keys |
.values() | the values |
.items() | key and value pairs |
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
Food
Transport
Data
46500
Food: ₦28,000
Transport: ₦12,500
Data: ₦6,000.items() is the one you'll use most: each round gives you the key and its value, unpacked into two variables. (Looping over the dictionary itself, for item in spending:, gives the keys.)
Finding the largest
max on a dictionary compares keys by default. To find the key with the largest value, tell it to compare using spending.get:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
Food
28000Counting with a dictionary
A very common job: count how often each value appears. Start with an empty dictionary and add 1 for each item, using get with a default of 0 for keys you haven't seen yet:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
{'Accounting': 3, 'Economics': 2, 'Law': 1}The first time Python sees "Accounting", counts.get("Accounting", 0) gives 0, so it becomes 1. Next time it gives 1, so it becomes 2, and so on.
Nested data
Values can be lists or other dictionaries. That's how real data is often shaped, for example data from websites and apps:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
ECO 201
IbadanRead it from left to right: student["address"] is the inner dictionary, and ["city"] looks inside that.
A list of dictionaries is a natural way to store a table, one dictionary per row:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
Adaeze
TobiSets: unique values
A set is a collection with no duplicates and no particular order. Write it with curly brackets (but no colons), or make one from a list with set():
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
3
TrueDuplicates disappear, so len(set(items)) counts distinct values. Sets also compare groups. Students taking each of two courses:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
['Musa', 'Tobi']
['Adaeze', 'Chidi', 'Musa', 'Tobi']
['Adaeze'](sorted turns each set into an ordered list, so the output is always the same.)
| Collection | Brackets | Ordered | Duplicates | Look up by |
|---|---|---|---|---|
| list | [ ] | yes | allowed | position |
| tuple | ( ) | yes | allowed | position (can't change) |
| dictionary | {key: value} | yes | keys unique | key |
| set | { } | no | not allowed | membership (in) |
When it goes wrong
print(student["Name"])Output
KeyError: 'Name'A key that isn't there. Keys must match exactly, capitals included. Use student.get("Name", "unknown") when a key might be missing.
empty = {}
print(type(empty))Output
<class 'dict'>{} is an empty dictionary, not a set. Make an empty set with set().
for item, amount in spending:
print(item, amount)Output
ValueError: too many values to unpack (expected 2)Forgetting .items(). Looping over a dictionary gives only the keys; add .items() to get pairs.
Summary
| You want to... | Write |
|---|---|
| make a dictionary | d = {"key": value, ...} |
| read a value | d["key"] |
| read safely | d.get("key", default) |
| add or change | d["key"] = value |
| remove | d.pop("key") |
| loop through pairs | for k, v in d.items(): |
| total of values | sum(d.values()) |
| key with the largest value | max(d, key=d.get) |
| count things | counts[x] = counts.get(x, 0) + 1 |
| distinct values | set(items) |
Try it
Practice
prices = {"rice": 52000, "beans": 38000, "garri": 15000}. What is sum(prices.values())?
Practice
Using the prices dictionary above, what does prices.get("yam", 0) give?
Practice
How many distinct cities are in ["Lagos", "Abuja", "Lagos", "Kano", "Ibadan", "Abuja"]?
Task
10 minWrite a vote counter: start with a list of at least eight votes for three candidates (names as text), count them into a dictionary with a loop and get, print each candidate's votes with .items(), and print the winner using max with key=. Paste your code.
Your work is checked for
- A list of at least eight votes
- Starts an empty dictionary
- A for loop over the votes
- Counts with get(..., 0) + 1
- Loops through .items()
- Finds the winner with max(..., key=...)
Earn your badge
Take the module check
Questions on this module. Pass and you earn the Python Dictionaries badge, free.
Create a free account to earn the badge