← Back to course
Code Crew G4 / Week 08 / Monday
1/6
Week 08 Β· List or dictionary?

Monday

A list of records
// Records and the right container
⏱ about 15 min

Monday: A list of records

The launch schedule is getting complicated. Every launch has a name, a gate and a time. Rocket tries three separate lists, then three separate dictionaries. He keeps mixing up which time goes with which gate.

Raven spreads out some index cards. On each card she writes one launch, with all its facts. "What do you notice?" she asks. "Each card is like a little dictionary. And the cards are in order, like a list."

Nova stacks the glowing cards in a neat row. "Would you like a hint? Python can do exactly that."

Records in a list

A record is a group of facts about one thing. A dictionary makes a great record.

Put many records in a list, and you have a list of dictionaries.

A long list can be split over several lines. Python waits for the closing bracket.

launches = [
    {"name": "Moon hop", "gate": 2, "time": "0900"},
    {"name": "Ring tour", "gate": 7, "time": "1300"},
]
print(launches[1]["gate"])
print(launches[0]["name"])
print(len(launches))
The screen shows
7
Moon hop
2
  1. launches[1] picks the second record from the list.
  2. ["gate"] looks up the gate key in that record.
  3. Read it left to right: list index first, then dictionary key.
launches[0]["gate"] gives
launches[1]["name"] gives
REACH THE FACT
  • Read the question.
  • Tap your answer.
Which line shows the time 1300?
What does len(launches) count?
Try it
Write a record card for a space trip you would like to take.
Use keys like place, days and crew.

Practice lab: the pod records

pods = [
    {"id": "A", "crew": 3, "deck": 1},
    {"id": "B", "crew": 5, "deck": 2},
    {"id": "C", "crew": 2, "deck": 2},
]
print(pods[2]["id"])
print(pods[1]["crew"])
print(pods[0]["deck"] + pods[2]["deck"])
What does pods[1]["crew"] give?
What does the last line show?
What does len(pods) give?
Which index holds the record for pod B?
RECORD CHECK
  • Read the question.
  • Tap your answer.
What does line 6 show?
What is pods[0]?
In pods[1]["crew"], what comes first?
Statement about podsTrue or false?
pods is a list.?
Each record in pods is a dictionary.?
pods["crew"] gives 3.?
len(pods[0]) counts the keys in record 0.?
WHY THIS EXERCISEpods needs an index first, because it is a list. len works on either one.
What number does print(pods[2]["crew"]) show?
WHY THIS EXERCISEPick the record with the index, then read the crew key.

Great work with records! Tomorrow you will loop through a whole list of them.