Python Tutorial: Nested Dictionaries 🎯

beginner
20 min

Python Tutorial: Nested Dictionaries 🎯

Welcome to our comprehensive guide on Nested Dictionaries in Python! This lesson is designed to help both beginners and intermediate learners understand and master this powerful data structure. Let's dive in!

Understanding Dictionaries 📝

A dictionary in Python is a collection of key-value pairs. It's useful for storing data in a way that's easy to access, update, and manipulate.

python
# Simple Dictionary Example my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

Nesting Dictionaries 💡

Nesting simply means putting one dictionary inside another. This can be useful for organizing complex data structures, like a database of user profiles or a multi-level menu system.

python
# Nested Dictionary Example nested_dict = { 'user1': {'name': 'Alice', 'email': 'alice@example.com'}, 'user2': {'name': 'Bob', 'email': 'bob@example.com'}, }

In the example above, we have a dictionary where the keys are usernames, and each value is another dictionary containing the user's name and email.

Accessing and Modifying Nested Dictionaries ✅

Accessing a nested dictionary works the same way as a regular dictionary, but you need to specify the key of the nested dictionary as well.

python
print(nested_dict['user1']['name']) # Output: Alice nested_dict['user1']['email'] = 'alice_new@example.com' # Updating the email for user1

Real-World Example: User Profiles 📝

Let's create a more practical example. We'll build a dictionary of user profiles for a website, where each user has a username, name, email, and a list of their favorite movies.

python
user_profiles = { 'user1': { 'name': 'Alice', 'email': 'alice@example.com', 'favorite_movies': ['The Shawshank Redemption', 'The Godfather'] }, 'user2': { 'name': 'Bob', 'email': 'bob@example.com', 'favorite_movies': ['Inception', 'Interstellar'] }, }

Now you can access a user's name, email, or favorite movies like so:

python
print(user_profiles['user1']['name']) # Output: Alice print(user_profiles['user1']['email']) # Output: alice@example.com print(user_profiles['user1']['favorite_movies']) # Output: ['The Shawshank Redemption', 'The Godfather']

Quiz Time! 💡

Quick Quiz
Question 1 of 1

What is a nested dictionary in Python?

Quick Quiz
Question 1 of 1

How do you access a nested dictionary?