Back to Python
2026-02-085 min read

Nested Dictionaries (Python Programming)

Learn Nested Dictionaries (Python Programming) step by step with clear examples and exercises.

Why This Matters

Python's dictionary data structure is a flexible and powerful tool for organizing and manipulating key-value pairs. However, when dealing with complex data structures like nested dictionaries, it becomes essential to understand their usage, benefits, and potential pitfalls. In this tutorial, we will delve into the world of Python nested dictionaries, exploring why they matter, prerequisites, core concepts, a worked example, common mistakes, practice questions, and frequently asked questions.

Benefits of Nested Dictionaries

Nested dictionaries are crucial in various real-world scenarios such as data analysis, web development, and game development. They allow you to create hierarchical structures that can efficiently store and manage complex data sets. For instance, when working with JSON files or handling large datasets, nested dictionaries prove indispensable due to their ability to organize data in a clear and concise manner.

Furthermore, nested dictionaries are often encountered during interviews, where they serve as a common topic for testing problem-solving skills and understanding of Python's data structures. Mastering nested dictionaries can help you tackle complex problems more effectively and stand out in the competitive job market.

Prerequisites

Before diving into nested dictionaries, it is essential to have a solid foundation in Python programming concepts:

  • Basic Python syntax (variables, data types, operators)
  • Control structures (if-else statements, loops)
  • Functions and modules
  • Understanding of lists and single-level dictionaries

Importance of Prerequisites

Having a strong foundation in the above concepts will make it easier to grasp the intricacies of nested dictionaries. It is recommended that you familiarize yourself with these topics before proceeding, as they form the building blocks for understanding more complex data structures.

Core Concept

A nested dictionary is a dictionary that contains another dictionary as its value. This allows you to create multi-layered data structures with key-value pairs within other key-value pairs. Here's an example of a simple nested dictionary:

nested_dict = {
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA"
}
}

In this example, nested_dict is a dictionary with three key-value pairs: name, age, and address. The value for the address key is another dictionary containing the keys street, city, and state.

To access values within nested dictionaries, you can use dot notation or indexing. For example:

print(nested_dict["name"]) # Outputs: John Doe
print(nested_dict["address"]["city"]) # Outputs: Anytown

Understanding Dot Notation and Indexing

Dot notation is a shorthand for accessing values in nested dictionaries, while indexing allows you to access values in lists or other iterable objects. Both methods can be used interchangeably but may not always be applicable depending on the structure of your nested dictionary.

Dot Notation Example

nested_dict = {
"person": {
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA"
}
}
}

print(nested_dict["person"]["name"]) # Outputs: John Doe

Indexing Example

nested_list = [{"name": "John Doe", "age": 30}, {"name": "Jane Smith", "age": 28}]
print(nested_list[0]["name"]) # Outputs: John Doe

Worked Example

Let's consider a more complex example where we create a nested dictionary to store information about multiple books and their authors.

books = {
"123": {
"title": "The Catcher in the Rye",
"author": "J.D. Salinger",
"publication_year": 1951,
"genre": ["Fiction", "Literature"]
},
"456": {
"title": "To Kill a Mockingbird",
"author": "Harper Lee",
"publication_year": 1960,
"genre": ["Fiction", "Literature"]
}
}

In this example, books is a nested dictionary containing two sub-dictionaries, each representing a book with its respective details. We can access the title of the first book as follows:

print(books["123"]["title"]) # Outputs: The Catcher in the Rye

Manipulating Nested Dictionaries

You can perform various operations on nested dictionaries, such as adding new key-value pairs, updating existing values, or deleting keys. These operations can be carried out using the same methods available for single-level dictionaries, with the added complexity of navigating through multiple layers of the nested structure.

Adding a New Book

books["789"] = {
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"publication_year": 1925,
"genre": ["Fiction", "Literature"]
}

Updating an Existing Book's Title

books["456"]["title"] = "Go Set a Watchman"

Deleting a Key from a Nested Dictionary

del books["123"]["genre"]

Common Mistakes

  • Forgetting to enclose dictionary values in curly braces: This will result in a syntax error.
  • Incorrect indentation when defining nested dictionaries: Python requires proper indentation for correct parsing of nested structures.
  • Attempting to access non-existent keys or keys at an incorrect level: Ensure that you are using the correct key and that it exists within the appropriate level of the nested dictionary.
  • Misunderstanding the difference between lists and nested dictionaries: While both can store multiple items, nested dictionaries provide a more structured approach for complex data sets.

Mistake 1: Syntax Error

Incorrect syntax

nested_dict = {

"name": John Doe,

"age": 30,

"address": {

"street": "123 Main St",

"city": "Anytown",

"state": "CA"

}

}


### Mistake 2: Indentation Error

Incorrect indentation

nested_dict = {

"name": "John Doe",

"age": 30,

"address":{

"street": "123 Main St",

"city": "Anytown",

"state": "CA"

}

}


### Mistake 3: Accessing Non-Existent Key

Incorrect key access

print(nested_dict["email"]) # Outputs: KeyError: 'email'

Practice Questions

  1. Create a nested dictionary to store information about multiple students, including their names, ages, and grades in different subjects.
  2. Given the following nested dictionary, write code to calculate and print the total number of books in the books list:
library = {
"books": [
{"title": "Book1", "author": "Author1"},
{"title": "Book2", "author": "Author2"},
{"title": "Book3", "author": "Author3"}
]
}
  1. Write a function that takes a nested dictionary as input and returns the total number of items in all lists contained within the dictionary.

FAQ

Q1: How do I create an empty nested dictionary?

A1: To create an empty nested dictionary, you can use multiple curly braces or nest a list of empty dictionaries:

empty_nested_dict = {} # Using multiple curly braces
empty_nested_list = [{}] # Nesting a list of empty dictionaries

Q2: How can I loop through all keys and values in a nested dictionary?

A2: You can use nested loops to iterate through all keys and values in a nested dictionary. Here's an example:

for key, value in nested_dict.items():
if isinstance(value, dict): # Check if the value is another dictionary
for subkey, subvalue in value.items():
print(f"Subkey: {subkey}, Subvalue: {subvalue}")
else:
print(f"Key: {key}, Value: {value}")
Nested Dictionaries (Python Programming) | Python | XQA Learn