Chapter 6 Dictctionaries
Chapter 6 Dictctionaries
Because this is a medium-speed alien, its position shifts two units to the right
Original x-position: 0
New x-position: 2
This technique is pretty cool: by changing one value in the alien’s dictionary, you can
change the overall behavior of the alien
For example, to turn this medium-speed alien into a fast alien, you would add this line:
alien_0['speed'] = 'fast'
Working with Dictionaries
This type of looping would work just as well if our dictionary stored the results from polling a
thousand or even a million people
Looping Through a Dictionary
Nesting happens when you store multiple dictionaries in a list, or a list of items as a
value in a dictionary.
You can nest dictionaries inside a list, a list of items inside a dictionary, or even a
dictionary inside another dictionary
A List of Dictionaries
The following code builds a list of three aliens
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
Nesting
A List of Dictionaries
We first create three dictionaries, each representing a different alien.
We store each of these dictionaries in a list called aliens 1.
Finally, we loop through the list and print out each alien:
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
Nesting
A List of Dictionaries
We use range()to create a fleet of 30 aliens
aliens = []
# Make 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("...")
# Show how many aliens have been created.
print(f"Total number of aliens: {len(aliens)}")
Nesting
A List of Dictionaries
{'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'}
...
These aliens all have the same characteristics
Python considers each one a separate object, allowing us to modify each alien individually
Nesting
A List of Dictionaries
We can add the following code to change the color, speed and points of the first 3 aliens
for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
Nesting
A List in a Dictionary
Useful to put a list inside a dictionary
You might describe a pizza that someone is ordering
You could store a list of the pizza’s toppings
A List in a Dictionary
The following output summarizes the pizza that we plan to build:
You ordered a thick-crust pizza with the following toppings:
mushrooms
extra cheese
Nesting
A Dictionary in a Dictionary
A dictionary can be nested inside a dictionary
users = {
'aeinstein': {'first': 'albert','last': 'einstein','location': 'princeton',},
'mcurie': {'first': 'marie','last': 'curie','location': 'paris',},
}
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()}")
Nesting
A Dictionary in a Dictionary
The following output is displayed
Username: aeinstein
Full name: Albert Einstein
Location: Princeton
Username: mcurie
Full name: Marie Curie
Location: Paris
Nesting
A Dictionary in a Dictionary
# Example shopping cart (items with quantity and price)
cart = {
}
Nesting
A Dictionary in a Dictionary
# Calculate the total price of the cart
total_price = 0
for item, details in cart.items(): # Outer loop: iterates through the cart dictionary
for key, value in details.items(): # Inner loop: iterates through item details
if key == "quantity":
quantity = value
price = value
total_price += quantity * price # Multiply quantity and price for each item
Output:
Total Price: $10.00
Explanation:
The outer loop iterates through each item in the cart (e.g., apple,
banana, orange).
The inner loop extracts the quantity and price from the dictionary for
each item.
The total price is calculated by multiplying the quantity by the price
for each item.