Show contents
Chapter 4 of 7 · 20 min
Lists and dictionaries
By the end of this chapter, you'll be able to
- Create, read and change a list
- Add items to a list and remove them
- Create a dictionary and access a value by its key
- Go through a list and a dictionary with for
Lists
A list is an ordered sequence of values. Each item has an index (its position), which starts at 0.
fruits = ["mango", "papaya", "guava"]
print(fruits[0]) # first item
print(fruits[-1]) # last item
print(len(fruits)) # number of items
fruits.append("pineapple") # adds at the end
fruits[1] = "lychee" # replaces the item at index 1
fruits.remove("mango") # removes the first occurrence
print(fruits)
mango
guava
3
['lychee', 'guava', 'pineapple']
append and remove are methods: functions attached to a data type, which you call with a dot.
Dictionaries
A dictionary associates keys with values, the way a phone book associates a name with a number. You write the key: value pairs between curly braces.
items() gives the pairs one by one, in the order they were added.
Text description of the animation
- A small grocery stock: each product (the key) is associated with a quantity (the value).
- The dictionary holds two pairs.
- We read the value of the key millet, subtract 2 and store the result under the same key.
- Assigning a key that doesn't exist yet adds a new pair.
- items() gives the pairs one by one, in the order they were added.
stock = {"rice": 12, "millet": 5}
stock["millet"] = stock["millet"] - 2
stock["maize"] = 8
for product, quantity in stock.items():
print(product, quantity)
print("sorghum" in stock) # does the key exist?
print(stock.get("sorghum", 0)) # the value, or 0 if the key is missing
rice 12
millet 3
maize 8
False
0
Combining the two
We often store a list of dictionaries: each dictionary describes one item.
students = [
{"name": "Awa", "grade": 15},
{"name": "Luis", "grade": 11},
{"name": "Mei", "grade": 17},
]
best = students[0]
for s in students:
if s["grade"] > best["grade"]:
best = s
print(best["name"], "has the best grade:", best["grade"])
Mei has the best grade: 17
Your turn
Mini-lab: counting wordsPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Worked exercise
Worked exercise: the basket
The basket is a list of dictionaries {"item": ..., "price": ..., "quantity": ...}. Write a function basket_total(basket) that returns the total to pay.
Hint 1
total = 0, then go through the basket with for.Hint 2
line["price"] * line["quantity"].Show the solution and common mistakes
def basket_total(basket):
total = 0
for line in basket:
total += line["price"] * line["quantity"]
return round(total, 2)
basket = [
{"item": "notebook", "price": 2.5, "quantity": 4},
{"item": "pen", "price": 1.2, "quantity": 3},
]
print(basket_total(basket))
13.6
total += x is a shortcut for total = total + x.
Common mistakes:
- Writing
line[price]without quotes: Python looks for a variablepriceand raises aNameError. - Forgetting
round: decimal calculations can display13.600000000000001, because of the way computers represent decimal numbers.
Summary
- 1A list is an ordered sequence; indexes start at 0.
- 2append adds at the end, remove removes a value, len gives the size.
- 3A dictionary associates keys with values: you read stock["rice"].
- 4items() goes through the key-value pairs; get() avoids an error if the key is missing.
- 5A list of dictionaries describes a collection of structured items.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.