Chapter 6 – Dictionaries
- can nest dictionaries inside lists, lists inside dictionaries, and even dictionaries inside other dictionaries
- understanding dictionaries allows you to model real-world objects more accurately
- for example, you can create a dictionary representing a person and then store as much information as you want about that person, such as their name, age, location, profession, etc
- you can store any two kinds of information that can be matched up, such as a list of words and their meaning, a list of people’s names and their favorite numbers, a list of mountains and their elevations
A simple dictionary
- can create a dictionary for a game featuring aliens with different colors and point values
alien.py
alien_0 = {‘color’: ‘green’, ‘points’: 5}
print(alien_0[‘color’])
print(alien_0[‘points’])
green
5
Working with dictionaries
- dictionary – collection of key-value pairs
- key – connected to a value, can be used to access the value associated with it
- a key’s value can be a number, string, list, or another dictionary
- in Python, a dictionary is wrapped in braces ({}) with a series of key-value pairs inside the braces
alien_0 = {‘color’: ‘green’, ‘points’: 5}
- key-value pair – set of values associated with each other, every key is collected with its value by a colon
- individual key-value pairs are connected by commas
- simplest dictionary has one key-value pair
alien_0 = {‘color’: ‘green’}
Accessing values in a dictionary
- give the name of the dictionary and then place the key inside a set of square brackets to get the value associated with a key
alien.py
alien_0 = {‘color’: ‘green’}
print(alien_0[‘color’])
green
- you can have an unlimited number of key-value pairs
alien_0 = {‘color’: ‘green’, ‘points’: 5}
- can access either value, if a player shoots down his alien, you can look up how many points they should earn
alien_0 = {‘color’: ‘green’, ‘points’: 5}
new_points = alien_0[‘points’]
print(f”You just earned {new_points} points!”)
You just earned 5 points!
- if you run this code every time an alien is shot down, the alien’s point value will be retrieved
Adding new key-value pairs
- dictionaries are dynamic structures, can add key-value pairs at any time
- to add a new pair, give the name of the dictionary followed by the new key in square brackets, along with the new value
- for example, adding the alien’s x- and y-coordinates to display the aline’s position on the screen
alien.py
alien_0 = {‘color’: ‘green’, ‘points’: 5}
print(alien_0)
alien_0[‘x_position’] = 0
alien_0[‘y_position’] = 25
print(alien_0)
{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘green’, ‘points’: 5, ‘x_position’: 0, ‘y_position’: 25}
- dictionaries retain the order in which they were defined
Starting with an empty dictionary
- sometimes better to start with an empty dictionary and define as you go
alien.py
alien_0 = {}
alien_0[‘color’] = ‘green’
alien_0[‘points’] = 5
print(alien_0)
{‘color’: ‘green’, ‘points’: 5}
- typically you would use an empty dictionary when storing user-supplied data or when writing code that generates a large number of key-value pairs automatically
Modifying values in a dictionary
- give the name of the dictionary with the key in square brackets and the new value if you want to modify a value in the dictionary
alien.py
alien_0 = {‘color’: ‘green’}
print(f”The alien is {alien_0[‘color’]}.”)
alien_0[‘color’] = ‘yellow’
print(f”The alien is now {alien_0[‘color’]}.”)
The alien is green.
The alien is now yellow.
- we can track the position of an alien moving at different speeds
alien_0 = {‘x_position’: 0, ‘y_position’: 25, ‘speed’: ‘medium’}
print(f”Original position: {alien_0[‘x_position’]}”)
# Move the alien to the right.
# Determine how far to move the alien based on its current speed.
if alien_0[‘speed’] == ‘slow’:
….x_increment = 1
elif alien_0[‘speed’] == ‘medium’:
….x_increment = 2
else:
….# This must be a fast alien.
….x_increment = 3
….# The new position is the old position plus the increment.
alien_0[‘x_position’] = alien_0[‘x_position’] = x_increment
print(f”New position: {alien_0[‘x_position’]}”)
- start by defining an alien with an initial x position and y position, and a speed of ‘medium’
- we omitted color and point values for simplicity, but this would work if we included those key-value pairs
- we print the original value of x_position to see how far the alien moves to the right
- an if-elif-else chain determines how far the alien should move to the right and assign this value to the variable x_increment
- if the alien’s speed is ‘slow’, it moves one unit to the right; if the speed is ‘medium’, it moves two units to the right; and if it’s ‘fast’, it moves three units to the right
- once the increment has been calculated, it’s added to the value of x_position
- the result is stored in the dictionary’s x_position
- because it’s a medium-speed alien, its position shifts two units to the right
Original x_position: 0
New x-position: 2
- 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’
- the if-elif-else block would then assign a larger value to x_increment the next time the code runs
Removing key-value pairs
- when you no longer need a piece of information that’s stored in a dictionary, you can use the del statement to completely remove a key-value pair
- all del needs is the name of the dictionary and the key that you want to remove
- for example, let’s remove the key ‘points’ from the alien_0 dictionary, along with its value
alien.py
alien_0 = {‘color’: ‘green’, ‘points’: 5}
print(alien_0)
del alien_0[‘points’]
print(alien_0)
- del statement tells Python to delete the key ‘points’ from the dictionary alien_0
- to remove the value associated with that key as well
- the output shows that the key ‘points’ and its value of 5 are deleted from the dictionary, but the rest of the dictionary is unaffected:
{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘green’}
- the key-value pair is removed permanently
A dictionary of similar objects
- the previous example involved storing different kinds of information about one object
- you can also use a dictionary to store one kind of information about many objects
- for example, a dictionary can store the results fo a simple poll
favorite_languages.py
favorite_languages = {
….’jen’: ‘python’,
….’sarah’: ‘c’,
….’edward’: ‘rust’,
….’phil’: ‘python’,
….}
- we’ve broken a larger dictionary into several lines
- each key is the name of a person who responded to the poll
- each value is their language choice
- when you need more than one line to define a dictionary, press enter after the opening brace, indent on the next line (four spaces) and write the first key-valye pair, followed by a comma
- press enter, your text editor should indent all subsequent key-value pairs automatically
- finally, add a closing brace on a new line after the last key-value pair once you’ve finished defining the dictionary, and indent it one level
- can use dictionary to look up a name of a person and their favorite language
favorite_languages.py
favorite_languages = {
….’jen’: ‘python’,
….’sarah’: ‘c’,
….’edward’: ‘rust’,
….’phil’: ‘python’,
….}
language = favorite_languages[‘sarah’].title()
print(f”Sarah’s favorite language is {language}.”)
Sarah’s favorite language is C.
Using get() to access values
- using keys in square brackets to retrieve the value you’re interested in will cause an error if the key doesn’t exist
alien_no_points.py
alien_0 = {‘color’: ‘green’, ‘speed’: ‘slow’}
print(alien_0[‘points’]
- results in a traceback error
- get() method – sets a default value that will be returned if the requested key doesn’t exist
- get() method requires a key as a first argument, as a second optional argument, you can pass the value to be returned if the key doesn’t exist
alien_0 = {‘color’: ‘green’, ‘speed’: ‘slow’}
point_value = alien_0.get(‘points’, ‘No point value assigned.’)
print(point_value)
- if the key ‘points’ exists, you’ll get a value
- if it doesn’t, you’ll get the default value
No point value assigned.
- consider using get() method instead of square brackets if there’s a chance the key might not exist
Looping through a dictionary
- can loop through all key-value [airs in a dictionary, through its keys or values
Looping through all key-value pairs
- example, dictionary storing user’s username, first name, and last name
user.py
user_0 = {
….’username’: ‘efermi’,
….’first’: ‘enrico’,
….’last’: ‘fermi’,
}
- can access any single piece of information about user_0, but what if you wanted to see everything stored in this user’s dictionary
- use a for loop
user_0 = {
….’username’: ‘efermi’,
….’first’: ‘enrico’,
….’last’: ‘fermi’,
}
for key, value in user_0.items():
….print(f”\nKey: {key}”)
….print(f”Value: {value}”)
- create names for the two variables that hold the key and value in each key-value pair to write a for loop in a dictionary
- can choose any names
- could work if you used abbreviations for the variable names
for k, v in user_0.items()
- second half of the for statement includes the name of the dictionary followed by the method items(), which returns a sequence of key-value pairs
- for loop then assigns each pairs to the provided variables
Key: username
Value: efermi
Key: first
Value: enrico
Key: last
Value: fermi
- back to the previous dictionary for favorite programming language, because the keys always refer to a person’s name and the value is always a language, we’ll use the variables name and language in the loop to make it easier to follow what’s happening
favorite_languages.py
favorite_languages = {
….’jen’: ‘python’,
….’sarah’: ‘c’,
….’edward’: ‘rust’,
….’phil’: ‘python’,
….}
for name, language in favorite_languages.items()
….print(f”{name.title()}’s favorite language is {language.title()}.”)
- descriptive names make it easier to see what the print() call is doing
Jen’s favorite language is Python.
Sarah’s favorite language is C.
Edward’s favorite language is Rust.
Phil’s favorite language is Python.
End of study session.