Nested Data Structures in Python

Vasudha Jha
The Engineering Gecko
2 min readMar 26, 2021

Python comes with a lot of built-in data structures like lists, sets, tuples, and dictionaries and because of its simplicity, Python makes it very easy to work with these data structures. In this post, I would like to discuss how to nest these data structures to create sophisticated types for managing data.

Let’s create a list to hold the names of the top three public universities in the USA.

universities = ['UCLA', 'UC Berkley', 'UMich']

While this works well to hold the university names, if we wish to associate additional information with each university such as its ranking, then a list of strings will not suffice. Instead, if we replace the list of strings with a list of dictionaries, we can hold more information in it, like university names and rankings.

For example, a dictionary with a university name and rank can be constructed like this:

{"name": "UCLA", "rank": 1}

Let’s go ahead and change our universities list to hold dictionaries instead of strings.

universities = [
{"name": "UCLA", "rank": 1},
{"name": "UC Berkley", "rank": 2},
{"name": "UMich", "rank": 3}
]

If we want to print information corresponding to UCLA, we can do so by using the index notation like so:

print(universities[0])

This will give us the following output:

{'name': 'UCLA', 'rank': 1}

Now, if we want to access the rank of UCLA, we can do so by:

ucla_rank = universities[0]['rank']

The above line of code can seem complicated but all that we are doing is accessing the dictionary {'name': 'UCLA', 'rank': 1} through universities[0] and then going one level deeper into the dictionary to access the rank through universities[0]['rank']

print(f"UCLA is ranked number {ucla_rank} in the country.")

This will give us the following output:

UCLA is ranked number 1 in the country.

Let’s iterate over the list of universities to display all the names and ranks.

for university in universities:
name = university['name']
rank = university['rank']
print(f"{name} is ranked number {rank} in the country.")

We get the following output:

UCLA is ranked number 1 in the country.
UC Berkley is ranked number 2 in the country.
UMich is ranked number 3 in the country.

Yay! We’ve successfully created and worked with a nested data structure.

While mentoring students new to programming, I have realized that many technical blog posts assume that the reader is an experienced programmer, which is not always the case. Hence, this is a beginner-friendly post intended to help people who are not only new to Python, but also to programming.

Please let me know about any other beginner-friendly topics about which you would like to learn.

Thank you for reading!

The original post is published here.

--

--

Vasudha Jha
The Engineering Gecko

An engineer, artist and writer, all at the same time, I suppose.