Dictionaries
Understanding dictionaries allows you to model real-world objects more accurately. A dictionary in Python is a collection of key-value pairs. Each key is connected to a value, and you can use a key to access the value associated with that key.
A Simple Dictionary
# Basic dictionary
alien = {'color': 'green', 'points': 5}
This dictionary stores two pieces of information about the alien: its color and point value.
Working with Dictionaries
Accessing Values in a Dictionary
alien = {'color': 'green', 'points': 5}
print(alien['color'])
print(alien['points'])
new_points = alien['points']
print(f"New points: {new_points}")
Output:
green
5
New points: 5
Adding New Key-Value Pairs
alien = {'color': 'green', 'points': 5}
alien['x_position'] = 0
alien['y_position'] = 25
print(alien)
Output:
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
Starting with an Empty Dictionary
alien = {}
print(alien)
Output:
{}
Modifying Values in a Dictionary
alien = {'color': 'green', 'points': 5}
alien['color'] = 'yellow'
print(alien)
Output:
{'color': 'yellow', 'points': 5}
Removing Key-Value Pairs
alien = {'color': 'green', 'points': 5}
print(alien)
del alien['points']
print(alien)
Output:
{'color': 'green', 'points': 5}
{'color': 'green'}
A Dictionary of Similar Objects
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
language = favorite_languages['sarah'].title()
print(f"Sarah's favorite language is {language}.")
Output:
Sarah's favorite language is C.
Using get() to Access Values
If you're not sure whether a key exists in a dictionary, you can use the get()
method to avoid a KeyError:
# This will cause a KeyError
alien_0 = {'color': 'green', 'speed': 'slow'}
print(alien_0['points']) # KeyError: 'points'
# Using get() to avoid errors
alien_0 = {'color': 'green', 'speed': 'slow'}
point_value = alien_0.get('points', 'No point value assigned.')
print(point_value)
Output:
No point value assigned.
The get()
method syntax: dictionary.get(key, default_value)
Looping Through a Dictionary
You can loop through all of a dictionary's key-value pairs, through its keys, or through its values.
Looping Through All Key-Value Pairs
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print(f"\nKey: {key}")
print(f"Value: {value}")
Output:
Key: username
Value: efermi
Key: first
Value: enrico
Key: last
Value: fermi
Looping Through All the Keys in a Dictionary
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys():
print(name.title())
Note: Looping through the keys is actually the default behavior when looping through a dictionary, so this code would have the same output:
for name in favorite_languages:
print(name.title())
Using Keys to Check Specific People
friends = ['phil', 'sarah']
for name in favorite_languages.keys():
print(f"Hi {name.title()}.")
if name in friends:
language = favorite_languages[name].title()
print(f"\t{name.title()}, I see you love {language}!")
Output:
Hi Jen.
Hi Sarah.
Sarah, I see you love C!
Hi Edward.
Hi Phil.
Phil, I see you love Python!
Checking Whether a Key Exists
if 'erin' not in favorite_languages.keys():
print("Erin, please take our poll!")
Output:
Erin, please take our poll!
Looping Through a Dictionary's Values
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("The following languages have been mentioned:")
for language in favorite_languages.values():
print(language.title())
Output:
The following languages have been mentioned:
Python
C
Ruby
Python
Avoiding Repetition with set()
If you want to see each unique value, you can use a set:
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
print(language.title())
Output:
The following languages have been mentioned:
Ruby
C
Python
You can also build a set directly:
languages = {'python', 'ruby', 'c', 'python'}
print(languages) # {'c', 'python', 'ruby'}
Nesting
Sometimes you'll want to store multiple dictionaries in a list, or a list of items as a value in a dictionary. This is called nesting.
A List of Dictionaries
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)
Output:
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
Creating a Fleet of 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)
# 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)}")
A List in a Dictionary
# Store information about a pizza being ordered
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}")
Output:
You ordered a thick-crust pizza with the following toppings:
mushrooms
extra cheese
A Dictionary in 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()}")
Output:
Username: aeinstein
Full name: Albert Einstein
Location: Princeton
Username: mcurie
Full name: Marie Curie
Location: Paris
Summary
In this chapter you learned how to:
- Define a dictionary and work with the information stored in it
- Access and modify elements in a dictionary, including adding new key-value pairs and removing them
- Use
get()
to access values safely - Loop through all key-value pairs, all keys, or all values
- Work with lists inside dictionaries, dictionaries inside lists, and dictionaries inside dictionaries
Dictionaries let you connect pieces of related information, enabling you to model real-world objects and situations accurately. As your programs become more complex, you'll find yourself using lists and dictionaries together to structure complex data in your programs.