Nested Data
Nested data means lists or dictionaries stored inside other lists or dictionaries. Read one layer at a time to reach a value inside.
A list of pairs
Each inner list below records a city and its temperature. Select one pair by its position in the outer list.
readings = [["Hobart", 12], ["Darwin", 30]]print(readings[0])This prints ['Hobart', 12]. Index 0 selects the first pair.
Reaching in step by step
Add a second index to select an item inside the pair. Read the indexes from left to right.
readings = [["Hobart", 12], ["Darwin", 30]]print(readings[0][0])print(readings[0][1])This prints Hobart, then 12. The first index chooses the reading; the second chooses its city or temperature.
When a chain confuses you, split it
Store the inner list in a variable to see each step separately.
readings = [["Hobart", 12], ["Darwin", 30]]reading = readings[0]print(reading)print(reading[1])This prints ['Hobart', 12], then 12. Here, reading[1] gives the same value as readings[0][1].
Unpack one pair
Select a pair, then unpack it into two named variables.
readings = [["Hobart", 12], ["Darwin", 30]]city, temperature = readings[0]print(city)print(temperature)This prints Hobart, then 12. The pair must contain exactly two items for these two names.
See also: Lists, Unpacking values.
Your turn
Print the temperature from the second reading. Then unpack that reading and print its city.
30 Darwin
readings = [["Hobart", 12], ["Darwin", 30]]# Print the nested temperature, unpack the second pair, and print its city.Advanced reading
- Nested dictionaries and lists — read values using a mixture of keys and positions.