Today we’ll be talking about the nested list and dictionary. Nested lists and dictionaries are often used to better structure your data. Theoretically there are no limits to the depth of nesting and you can have a list inside another list, which is inside yet another list, which itself also is inside another list, etc. Confusing? Because it is or rather it may quickly become if you stop using common sense when structuring your code using nested lists and dictionaries. We’re going to see a more complex example in a moment. But let’s start simple.
Table of Contents
A Simple Nested List
Lists and dictionaries may be nested. Here’s a simple example of a nested list. Watch how indices are used.
teams = [["Ben", "Bob", "Mike"], ["Ann", "Sue"], ["Ron", "Sarah", "Edwin"]]
print(f"In {teams[0][0]}'s team {teams[0][2]} is the oldest.")
So, there are two indices, one for each level of nesting. The first index is 0, so it refers to the first element in the outer list, which is the inner list [“Ben”, “Bob”, “Mike”]. The second index refers to the appropriate element inside this list, so the element teams[0][0] is “Ben” and teams[0][2] is “Mike”.
The output is:
In Ben's team Mike is the oldest.
A Simple Nested Dictionary
Now a simple nested dictionary:
worker = {"name": {"first": "Jane", "last": "Jackson"},
"address": {"country": "USA", "city": "Denver"},
"age": 57}
print(f'Mrs. {worker["name"]["last"]}, aged {worker["age"]}, lives in {worker["address"]["city"]}.')
Now there are two keys, again one for each level of nesting. The output is:
Mrs. Jackson, aged 57, lives in Denver.
A More Complex Example
And now a more complex example: A dictionary that contains simple elements, nested lists and nested dictionaries. Such complicated structures are seldom used, but it’s just to illustrate how the particular elements can be retrieved:
animals = {"species": {"english": "wolf", "latin": "Canis lupus"},
"class": "mammals",
"habitats": ["forests", "tundras", "grasslands"],
"dimensions": {"body": {"length": 150, "height": 80},
"tail": {"length": 40}}}
print("Latin name: " + animals["species"]["latin"])
print("Class: " + animals["class"])
print("Main habitat: " + animals["habitats"][0])
print("Body height: " + str(animals["dimensions"]["body"]["height"]))
The output is:
Latin name: Canis lupus
Class: mammals
Main habitat: forests
Body height: 80
Operations on Nested Lists and Dictionaries
You can perform operations on particular nested lists and dictionaries:
animals = {"species": {"english": "wolf", "latin": "Canis lupus"},
"class": "mammals",
"habitats": ["forests", "tundras", "grasslands"],
"dimensions": {"body": {"length": 150, "height": 80},
"tail": {"length": 40}}}
animals["species"]["french"] = "loup" # add element to dictionary
animals["habitats"].append("deserts") # append to list
animals["dimensions"]["tail"]["length"] *= 1.5 # augmented assignment
print("Names: " + str(animals["species"]))
print("Habitats: " + str(animals["habitats"]))
print("Tail length: " + str(animals["dimensions"]["tail"]["length"]))
The output is:
Names: {'english': 'wolf', 'latin': 'Canis lupus', 'french': 'loup'}
Habitats: ['forests', 'tundras', 'grasslands', 'deserts']
Tail length: 60.0
Naturally you should avoid overcomplicating things and usually you won’t use lists or dictionaries with so many levels of nesting on a regular basis. I hope, though, that you will be familiar with them if you come across them in code.
Here’s the video version: