Session 4 of 5 · 60 minutes
Lists and Dictionaries
Keep many values together in a list, and look things up by name in a dictionary.
Goals
By the end of this session you can:
- Create a list, read items by position, add and remove items
- Loop over every item in a list
- Create a dictionary and look up a value by its key
- Choose between a list and a dictionary for a job
Words to know
- list
- An ordered collection of values, written in square brackets.
- index
- The position of an item in a list. The first item is index 0.
- dictionary
- A collection of key and value pairs, written in curly braces.
- key
- The label you use to look up a value in a dictionary.
- method
- A function that belongs to a value, like fruits.append("fig").
The lesson
Step 1: A list holds many values
So far each variable has held one value. A list holds many, in order.
fruits = ["apple", "pear", "fig"]
print(fruits)
print(fruits[0])
print(fruits[2])
print(len(fruits))['apple', 'pear', 'fig']
apple
fig
3Each item has an index, its position, starting at 0. fruits[0] is the first item. A negative index counts from the end: fruits[-1] is the last.
Step 2: Changing a list
fruits = ["apple", "pear", "fig"]
fruits.append("plum")
fruits.remove("pear")
fruits[0] = "mango"
print(fruits)['mango', 'fig', 'plum']append()adds to the end.remove()takes out the first matching item.- Assigning to an index replaces that item.
Step 3: Looping over a list
You don’t need range() to go through a list. Just loop over the list itself.
scores = [80, 95, 70]
total = 0
for s in scores:
total += s
print("Average:", total / len(scores))Average: 81.66666666666667You can also ask whether something is in a list:
pets = ["cat", "dog"]
print("dog" in pets)
print("fish" in pets)True
FalseStep 4: A dictionary looks things up by name
A list finds things by position. A dictionary finds things by a key. It stores pairs: a key and its value.
prices = {"tea": 2, "milk": 3}
print(prices["milk"])
prices["juice"] = 4
print(prices)3
{'tea': 2, 'milk': 3, 'juice': 4}Check if a key exists before you use it, otherwise Python raises a KeyError:
if "cake" in prices:
print(prices["cake"])
else:
print("No cake today.")No cake today.Loop over a dictionary with .items():
for item, price in prices.items():
print(f"{item}: ${price}")tea: $2
milk: $3
juice: $4Step 5: Which one should I use?
| Use a list when… | Use a dictionary when… |
|---|---|
| order matters | you look things up by a label |
| you have many similar items | each item has a name and a value |
["red", "green", "blue"] | {"red": "#ff0000", "green": "#00ff00"} |
You can even combine them. A list of dictionaries is a tiny table:
students = [
{"name": "Amara", "grade": 7},
{"name": "Jabari", "grade": 8},
]
for s in students:
print(s["name"], "is in grade", s["grade"])Amara is in grade 7
Jabari is in grade 8Exercise
My top five
- Make a list of your five favorite songs, books or games.
- Print the first and last item using an index.
- Add a sixth item with
append(), then remove the second one withremove(). - Use a
forloop to print the final list with numbers, like1. Title.
Need a hint?
The last item is my_list[-1]. For numbering, use enumerate(my_list, start=1) or a counter variable.
Small project
Snack shop
Build an ordering program for a school snack shop using a dictionary of prices.
- Create a dictionary called
menuwith at least four snacks and their prices, like"apple": 1.5. - Print the menu so the customer can see it.
- Use a
whileloop to ask what the customer wants. Typedoneto finish. - If the snack is in the menu, add its price to a running
totaland add its name to a list calledorder. If not, printSorry, we don't sell that. - At the end print the order list and the total.
Stretch it: Let the customer type a quantity, like 3, and multiply the price.
Quiz
Check your understanding
Pick one answer for each question. Your score appears right in the page; nothing is sent anywhere.
Feedback on this lesson
Teachers and students: tell us what worked and what didn't. We read this to improve the curriculum.
Received
Thank you for the feedback.
The Education team reviews lesson feedback to improve the curriculum.
Preview mode: this form is not connected to a destination yet, so nothing was sent. Set its web address in src/data/config.json.