- can use a for loop and an if statement to change the color of the aliens
# 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)
print(“…”)
- slice only includes the first three aliens we want to modify
- can write an if statement to make sure we’re only modifying green aliens
- if gree, we change the color to yellow, the speed to medium, and the point value to 10
{‘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’}
…
- can expand loop by adding an elif block that turns the yellow aliens into red, fast-moving ones worth 15 points each
for alien in aliens[0:3]:
….if alien[‘color’] == ‘green’:
……..alien[‘color’] = ‘yellow’
……..alien[‘speed’] = ‘medium’
……..alien[‘points’] = 10
….elif alien[‘color’] == ‘yellow’:
……..alien[‘color’] = ‘red’
……..alien[‘speed’] = ‘fast’
……..alien[‘points’] = 15
- common to store a number of dictionaries in a list when each dictionary contains many kinds of information about one object
- for example, creating a dictionary for each user on a site and storing individual dictionaries in a list called users
- due to all dictionaries in the list having identical structure, you can loop through the list and work with each dictionary object in the same way
A list in a dictionary
- sometimes it’s more useful to put a list inside a dictionary rather than putting a dictionary inside a list
- for example, consider how you might describe a pizza someone is ordering
- if you were to only use a list, all you could store is a list of pizza toppings
- with a dictionary, a list of toppings can be one aspect of the pizza
- the following example stores two kinds of information for each pizza: a type of crust and a list of toppings
- list of toppings is a value associated with the key toppings
- to use the items in the list, we give the name of the dictionary and the key toppings, as we would any value in a dictionary
- instead of returning a single value, we get a list of toppings
pizza.py
# Store information about a pizza being ordered.
pizza = {
….’curst’: ‘thick’,
….’toppings’: [‘mushrooms’, ‘extra cheese’],
….}
# Summarize the order.
print(f”You ordered a {pizza[‘curst’]}-crust pizza “
….”with the following toppings:”)
for topping in pizza[‘toppings’]:
….print(f”\t{topping}”)
- we begin with a dictionary that holds information about a pizza that has been ordered
- one key in the dictionary is crust and the value is the string thick
- next key toppings has a list as its value that stores all requested toppings
- we summarize the order before building the pizza
- when you need to break up a long line in a print() call, choose a spot and end the line with a quotation mark
- indent the next line, add an opening quotation mark, and continue the string
- Python will automatically combine all of the strings it finds inside the parentheses
- use a for loop to print the toppings
- use key toppings to access the list of toppings
You ordered a thick-crust pizza with the following toppings:
….mushrooms
….extra cheese
- you can nest a list inside a dictionary anytime you want more than one value to be associated with a single key in a dictionary
- in the earlier example of favorite programming languages, if we were to store each person’s responses in a list, people could choose more than one language
- when we loop through the dictionary, the value associated with each person would be a list of languages rather than a single language
- inside the dictionary’s for loop we use another for loop to run through the list of languages associated with each person
favorite_languages.py
….favorite_languages = {
….’jen’: [‘python’, ‘rust’],
….’sarah’: [‘c’],
….’edward’: [‘rust’, ‘go’],
….’phil’: [‘python’, ‘haskell’],
….}
for name, languages in favorite_languages.items():
….print(f”\n{name.title()]’s favorite languages are:”)
for language in languages:
….print(f”\t{language.title()}”)
- value associated with each name in favorite_languages is now a list
- we use variable name languages to hold each value from he dictionary, because each value will be a list
- inside the main dictionary lop, we use another for loop to run through each person’s list of favorite languages
Jen’s favorite languages are:
….Python
….Rust
Sarah’s favorite languages are:
….C
Edward’s favorite languages are:
….Rust
….Go
Phil’s favorite languages are:
….Python
….Haskell
- to refine this program even further, you could include an if statement at the beginning of the dictionary’s for loop to see whether each person has more than one favorite language by examining the value of len*(languages)
- if a person has more than one favorite, the output would stay the same
- if the person has only one favorite language, you could change the wording to reflect that
- for example, “Sarah’s favorite language is C.”
- you shouldn’t nest lists and dictionaries too deeply
A dictionary in a dictionary
- you can nest a dictionary inside another dictionary, but your code can get too complicated
- for example, users on a site, each with a unique username, you can use the usernames as the keys in a dictionary
- you can then store information about each user by using a dictionary as the value associated with their username
many_users.py
user = {
….’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()}”)
- first defined a dictionary, called users, with two keys: one each for the usernames
- the value associated with each key is a dictionary that includes each user’s first name, last name, and location
- we loop through the users dictionary, Python assigns each key to the variable username, and the dictionary associated with each username is assigned to the variable user_info
- once inside the main dictionary loop, we print the username
- then we start accessing the inner dictionary
- the variable user_info, has three keys: first, last, and location
- use each key to generate a neatly formatted full name and location and print he summary of what we know
Username: aeinstein
….Full name: Albert Einstein
….Location: Princeton
Username: mcurie
….Full name: Marie Curie
….Location: Paris
Summary
- learned how to define. dictionary and how to work with info inside
- learned how to access and modify individual elements in a dictionary and how to loop through all of the information in a dictionary
- learned to loop through a dictionary’s key-value pairs, keys, and values
- learned how to nest multiple dictionaries in a list, nest lists in a dictionary, and nest a dictionary inside a dictionary