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!
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.
# Simple Dictionary Example
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}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.
# 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 a nested dictionary works the same way as a regular dictionary, but you need to specify the key of the nested dictionary as well.
print(nested_dict['user1']['name']) # Output: Alice
nested_dict['user1']['email'] = 'alice_new@example.com' # Updating the email for user1Let'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.
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:
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']What is a nested dictionary in Python?
How do you access a nested dictionary?