Python- Day 19- DICTIONARIES {_} “ Working with Nested Data Structures”

Nidhi Ashtikar
4 min readOct 22, 2024

--

Nesting is an advanced concept in Python where you store multiple dictionaries in a list or a list of items as a value inside a dictionary.

This allows for highly flexible data structures.

A List of Dictionaries:

You might need to manage multiple objects of the same kind, like a group of aliens in a game.

Instead of creating a separate dictionary for each object, you can store them all in a list.

For example, you can store details of three aliens in a list of dictionaries like this:

# Create three dictionaries representing different aliens
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}

# Store the dictionaries in a list
aliens = [alien_0, alien_1, alien_2]

# Loop through the list and print each alien
for alien in aliens:
print(alien)

>>

{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}

You can even generate a large number of similar objects automatically. Here’s how to create a fleet of 30 green aliens:

# Make an empty list to store aliens
aliens = []

# Generate 30 green aliens
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)

# Show the first 5 aliens
for alien in aliens[:5]:
print(alien)

print(f"Total number of aliens: {len(aliens)}")

>>

{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
Total number of aliens: 30

This program creates 30 identical aliens and prints the first five. I

If you want to modify a few of them (say, change the first three to yellow aliens), you can use an if statement to selectively modify them:

# Make an empty list for storing aliens.

aliens = []

# Make 30 green aliens.

for alien_number in range (30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)

for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10

# Show the first 5 aliens.

for alien in aliens[:5]:
print(alien)

>>

{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}

This will update the first three aliens to yellow, medium-speed ones worth 10 points.

A List Inside a Dictionary:

Sometimes you might need to store multiple values for a single key in a dictionary.

For example, when ordering a pizza, you might want to store both the crust type and a list of toppings:

# Store information about a pizza
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}

# Summarize the order
print(f"You ordered a {pizza['crust']}-crust pizza with the following toppings:")
for topping in pizza['toppings']:
print(f"\t{topping}")

>>

You ordered a thick-crust pizza with the following toppings:
mushrooms
extra cheese

A Dictionary Inside a Dictionary:

Sometimes you might want to nest a dictionary inside another dictionary.

For instance, if you are managing user profiles on a website, you can store each user’s details like this:

# Dictionary of users
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}

# Loop through users and print information
for username, user_info in users.items():
print(f"\nUsername: {username}")
full_name = f"{user_info['first']} {user_info['last']}"
location = user_info['location']

print(f"\tFull name: {full_name.title()}")
print(f"\tLocation: {location.title()}")

>>

Username: aeinstein
Full name: Albert Einstein
Location: Princeton

Username: mcurie
Full name: Marie Curie
Location: Paris

Nesting lists and dictionaries allow for complex and dynamic data structures, making it easier to store and manipulate related information. However, be careful not to nest too deeply, as it can make the code difficult to manage.

If you found this guide helpful then do click on 👏 the button.

Follow for more Learning like this 😊

If there’s a specific topic you’re curious about, feel free to drop a personal note or comment. I’m here to help you explore whatever interests you!

Thanks for spending your valuable time learning to enhance your knowledge!

--

--

Nidhi Ashtikar
Nidhi Ashtikar

Written by Nidhi Ashtikar

Experienced AWS DevOps professional with a passion for writing insightful articles.

No responses yet