Rocket wants the command tree saved in the fleet computer. "Do I need a new kind of variable?" he asks.
Raven remembers the cargo dictionary. "What do you notice about each person in the tree?"
"Each one has a name and a list of crew," Rocket says. "A dictionary with a list inside!"
"And the list holds more dictionaries," Raven adds.
Nova sparkles. "Here is a hint. Read the brackets from the outside in, one step at a time."
Each node is a dictionary with two keys. "name" holds the person. "crew" holds a list of child nodes.
A leaf has an empty crew list. Read the program slowly, and match it to the table from Monday.
fleet = {
"name": "Ada",
"crew": [
{"name": "Bo", "crew": [
{"name": "Cy", "crew": []},
{"name": "Dee", "crew": []},
]},
{"name": "Eve", "crew": [
{"name": "Fen", "crew": []},
{"name": "Gil", "crew": []},
{"name": "Hal", "crew": []},
]},
],
}
print(fleet["name"])
print(fleet["crew"][0]["name"])
print(fleet["crew"][1]["crew"][2]["name"])
print(len(fleet["crew"])) Output: Ada Bo Hal 2
| Statement | True or false? |
|---|---|
| A leaf node has crew equal to []. | ? |
| fleet["crew"][0] is a name. | ? |
| Every node has the same two keys. | ? |
ship = {
"name": "Ship",
"parts": [
{"name": "Deck A", "parts": [
{"name": "Lab", "parts": []},
{"name": "Dock", "parts": []},
]},
{"name": "Deck B", "parts": [
{"name": "Bridge", "parts": []},
{"name": "Hold", "parts": []},
]},
],
}
print(ship["parts"][1]["name"])
print(ship["parts"][0]["parts"][1]["name"])
print(len(ship["parts"][1]["parts"])) | Statement | True or false? |
|---|---|
| Every node in ship has a name key and a parts key. | ? |
| ship["parts"][0] is the text Deck A. | ? |
| Hold is a leaf. | ? |
| The ship tree uses parts where the fleet uses crew. | ? |
Super! You stored a whole tree with dictionaries and lists. Tomorrow we count every node with recursion.