Learning Hub/Python/Session 4

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.

Python
fruits = ["apple", "pear", "fig"]
print(fruits)
print(fruits[0])
print(fruits[2])
print(len(fruits))
Output
['apple', 'pear', 'fig']
apple
fig
3

Each 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

Python
fruits = ["apple", "pear", "fig"]
fruits.append("plum")
fruits.remove("pear")
fruits[0] = "mango"
print(fruits)
Output
['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.

Python
scores = [80, 95, 70]
total = 0
for s in scores:
    total += s
print("Average:", total / len(scores))
Output
Average: 81.66666666666667

You can also ask whether something is in a list:

Python
pets = ["cat", "dog"]
print("dog" in pets)
print("fish" in pets)
Output
True
False

Step 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.

Python
prices = {"tea": 2, "milk": 3}
print(prices["milk"])
prices["juice"] = 4
print(prices)
Output
3
{'tea': 2, 'milk': 3, 'juice': 4}

Check if a key exists before you use it, otherwise Python raises a KeyError:

Python
if "cake" in prices:
    print(prices["cake"])
else:
    print("No cake today.")
Output
No cake today.

Loop over a dictionary with .items():

Python
for item, price in prices.items():
    print(f"{item}: ${price}")
Output
tea: $2
milk: $3
juice: $4

Step 5: Which one should I use?

Use a list when…Use a dictionary when…
order mattersyou look things up by a label
you have many similar itemseach 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:

Python
students = [
    {"name": "Amara", "grade": 7},
    {"name": "Jabari", "grade": 8},
]
for s in students:
    print(s["name"], "is in grade", s["grade"])
Output
Amara is in grade 7
Jabari is in grade 8

Exercise

My top five

  1. Make a list of your five favorite songs, books or games.
  2. Print the first and last item using an index.
  3. Add a sixth item with append(), then remove the second one with remove().
  4. Use a for loop to print the final list with numbers, like 1. 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.

  1. Create a dictionary called menu with at least four snacks and their prices, like "apple": 1.5.
  2. Print the menu so the customer can see it.
  3. Use a while loop to ask what the customer wants. Type done to finish.
  4. If the snack is in the menu, add its price to a running total and add its name to a list called order. If not, print Sorry, we don't sell that.
  5. 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.

  1. Question 1What does fruits[0] give you for fruits = ["apple", "pear", "fig"] ?
  2. Question 2Which line adds "plum" to the end of the list fruits?
  3. Question 3What does len([4, 8, 15, 16]) return?
  4. Question 4Given prices = {"tea": 2, "milk": 3} what is prices["milk"] ?
  5. Question 5Which is the best choice to store each student's phone number so you can find it by name?