Blog Post #70: Nesting 101: How to Structure Complex Data with Dictionaries and Lists

So far, our lists have contained simple items like numbers and strings, and our dictionary values have been simple as well. But what happens when the data we need to store is more complex? What if a user has a list of interests, or we have a list of users, where each user is a complex object?

This is where the power of nesting comes in. In this post, we’ll learn how to create sophisticated, hierarchical data structures by placing lists inside dictionaries, dictionaries inside lists, and even dictionaries inside other dictionaries.

Pattern 1: A List Inside a Dictionary

This is a very common pattern for when a single key needs to hold multiple, related values. For example, a user can have multiple hobbies, a blog post can have multiple tags, or a movie can have multiple actors.

Let’s model a user profile where we want to store a list of their interests.

user_profile = {
    "name": "Bob",
    "age": 28,
    "interests": ["hiking", "coding", "reading", "gaming"]
}

To access the data, you first use the dictionary key to get the list, and then you can use a list index to get a specific item from that list.

# Get the whole list of interests
hobbies = user_profile["interests"]
print(f"Bob's hobbies are: {hobbies}")

# Get the first hobby from the list (using index 0)
first_hobby = user_profile["interests"][0]
print(f"His first hobby is: {first_hobby}")

The output will be:

Bob's hobbies are: ['hiking', 'coding', 'reading', 'gaming']
His first hobby is: hiking

Pattern 2: A Dictionary Inside a List

This is arguably one of the most common data structures you’ll encounter when working with data from databases or APIs. It’s perfect for representing a collection of similar, structured objects. Think of a list of employees, a list of products, or a list of search results.

users = [
    { "id": 1, "name": "Alice", "role": "Admin" },
    { "id": 2, "name": "Bob", "role": "User" },
    { "id": 3, "name": "Charlie", "role": "User" }
]

Here, users is a list, and each item in the list is a dictionary representing one user. To access the data, you first use an integer index to select the dictionary you want from the list, and then you use a string key to get a value from that dictionary.

# Get the first user (which is a dictionary)
first_user = users[0]
print(f"The first user's dictionary is: {first_user}")

# Get the name of the second user (at index 1)
second_user_name = users[1]["name"]
print(f"The second user's name is: {second_user_name}")

The output will be:

The first user's dictionary is: {'id': 1, 'name': 'Alice', 'role': 'Admin'}
The second user's name is: Bob

Pattern 3: A Dictionary Inside a Dictionary

This pattern is great for grouping related information together under a single key, creating logical sub-categories within your data.

user_profile = {
    "username": "dave_c",
    "email": "dave@example.com",
    "address": {
        "street": "123 Python Lane",
        "city": "Codeville",
        "zipcode": "12345"
    }
}

To access the nested data, you simply chain the keys together in square brackets.

# Get the nested address dictionary
user_address = user_profile["address"]
print(f"The user's address is: {user_address}")

# Get just the city from the nested dictionary
user_city = user_profile["address"]["city"]
print(f"The user lives in: {user_city}")

The output will be:

The user's address is: {'street': '123 Python Lane', 'city': 'Codeville', 'zipcode': '12345'}
The user lives in: Codeville

What’s Next?

You can now structure complex, real-world data by nesting lists and dictionaries. Understanding these patterns—lists in dictionaries, dictionaries in lists, and dictionaries in dictionaries—is a huge step towards being able to model almost any kind of information.

Now that we can build these complex dictionaries, we also need to know how to manage them. Just like with lists, we often need to remove data. In Post #71, we will explore the essential dictionary methods for removing key-value pairs.

Author

Debjeet Bhowmik

Experienced Cloud & DevOps Engineer with hands-on experience in AWS, GCP, Terraform, Ansible, ELK, Docker, Git, GitLab, Python, PowerShell, Shell, and theoretical knowledge on Azure, Kubernetes & Jenkins. In my free time, I write blogs on ckdbtech.com

Leave a Comment