Nested Data
A list or dictionary can contain other lists or dictionaries. This is called nested data. Read it one layer at a time: first select a container, then an item inside it.
A list of pairs
Each inner list below records a city and its temperature:
readings = [["Hobart", 12], ["Darwin", 30]]
print(readings[0])
print(readings[0][0])
print(readings[0][1])
readings[0] selects ["Hobart", 12]. The next index selects an item from that pair: position zero is the city and position one is the temperature.
Unpack one pair
reading = ["Hobart", 12]
city, temperature = reading
print(city)
print(temperature)
The first item goes into city; the second goes into temperature. There must be exactly two items for these two names. In an indexed loop, use city, temperature = readings[i] after checking that i is a valid position. See Unpacking Values for more examples.
A dictionary inside a dictionary
state = {
"round_no": 4,
"banked_money": {"Alice": 30, "Bob": 55},
}
print(state["banked_money"])
Reaching in step by step
Chain the lookups from left to right. state["banked_money"] is itself a
dictionary, so you can index it again:
state = {
"banked_money": {"Alice": 30, "Bob": 55},
}
print(state["banked_money"]["Bob"])
Read it left to right: from state, get banked_money; from that, get Bob.
A list inside a dictionary
state = {
"players_out": ["Alice", "Cara"],
}
print(state["players_out"][0])
print("Cara" in state["players_out"])
When a chain confuses you, split it
If a chain is hard to read, pull it apart: store the first lookup in a
variable, print it to see what you've got, then index that:
state = {
"banked_money": {"Alice": 30, "Bob": 55},
}
money = state["banked_money"]
print(money)
print(money["Bob"])
money holds the inner dictionary, so money["Bob"] finishes the job. It
gives the same answer as state["banked_money"]["Bob"] — a long chain is just
several small lookups written together.
See also: Dictionaries, Lists.
Your turn
Print the temperature from the second reading. Then unpack that reading and print its city.
readings = [["Hobart", 12], ["Darwin", 30]]
# Print the nested temperature, unpack the second pair, and print its city.
Expected output
30
Darwin
Practise this in the free Python course, where every exercise checks your code instantly.