Skip to content
Home » Nested List and Dictionary Basics

Nested List and Dictionary Basics

Spread the love

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.

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.")
nested list

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.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

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

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

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"]))

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

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:


Spread the love

Leave a Reply