← Python lessons

Python Nested Dictionaries and Lists

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

Nested dictionaries store dictionaries inside other dictionaries. Combine key and position lookups to read values from dictionaries and lists.

Read Nested data, Dictionaries and Lists first. This lesson follows a lookup through each container. Run each example on its own: it creates all its data and needs no imports, files or helper functions.

A dictionary inside a dictionary

Use a nested dictionary to group related values under a label, such as banked scores. Choose dictionary keys when names identify values; choose list positions when order identifies them.

Use a key to select the inner dictionary, then another key to select its value.

state = {"banked_money": {"Alice": 30, "Bob": 55}}
print(state["banked_money"])
print(state["banked_money"]["Bob"])

This prints {'Alice': 30, 'Bob': 55}, then 55. state["banked_money"] returns a dictionary, so the next brackets use its key "Bob". The key "Bob" belongs to that inner dictionary, not to state.

Split a chain into steps

Store an intermediate result when you want to inspect it or read several of its values.

state = {"banked_money": {"Alice": 30, "Bob": 55}}
money = state["banked_money"]
print(money)
print(money["Bob"])

This prints the same dictionary and 55. money refers to the inner dictionary; this assignment does not copy it.

A list inside a dictionary

Choose each lookup from the container's type: a dictionary takes a key; a list takes a position. Here, state["players_out"] returns a list, so the next brackets use index 0, not a player name. Membership checks also work on the selected list.

state = {"players_out": ["Alice", "Cara"]}
print(state["players_out"][0])
print("Cara" in state["players_out"])

This prints Alice, then True. Using state["players_out"]["Alice"] would raise TypeError: the inner list needs an integer index.

Check before reaching further

An existing outer key does not guarantee that an inner list contains any items. Check the list's length before reading its first item.

state = {"players_out": []}
players = state["players_out"]
if len(players) > 0:
    print(players[0])
else:
    print("No players out")

This prints No players out. Without the check, players[0] would raise IndexError. A missing dictionary key raises KeyError instead.

These fixed examples assume the outer keys exist and hold the shown types. Data from elsewhere may need checks at every layer.

See also: Data validation, JSON.

Your turn

Print Bob's banked amount. Then store the players_out list in players, print its first name, and print whether "Cara" is in it.

state = {
    "banked_money": {"Alice": 12, "Bob": 25},
    "players_out": ["Bob", "Cara"],
}
# Read Bob's amount, store the inner list, and print its first name and membership check.

Expected output

25
Bob
True