This article is participating in Python Theme Month. See the link for details
In this article, you’ll learn about the Python dictionary that correlates related information and how to access and modify the information in the dictionary.
- There is almost no limit to the amount of information stored in a dictionary, and we will demonstrate how to traverse the data in a dictionary.
A simple dictionary
- A simple dictionary that stores information about aliens:
alien_0 = {'color': 'green'.'points': 5}
Copy the code
Use a dictionary
- In Python, a dictionary is a series of key-value pairs.
- Each key is associated with a value that can be accessed using a key.
- The values associated with keys can be numbers, strings, lists, or even dictionaries.
- In fact, you can use any Python object as a value in a dictionary.
Access the values in the dictionary
alien_0 = {'color': 'green'.'points': 5}
print(alien_0['color'])
print(alien_0['points'])
Copy the code
- You can visit aliens
alien_0
Color and score. If the player shoots the alien, he gets points:
alien_0 = {'color': 'green'.'points': 5}
new_points = alien_0['points']
print(f"You just earned {new_points} points!")
Copy the code
Add key-value pairs
- A dictionary is a dynamic structure into which key-value pairs can be added at any time.
- To add a key-value pair, specify the dictionary name, the key enclosed in square brackets, and the associated value.
- Add two items of information to the dictionary below: the alien’s X and Y coordinates:
alien_0 = {'color': 'green'.'points': 5}
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
Copy the code
Start by creating an empty dictionary
- Sometimes it is convenient to add key-value pairs to an empty dictionary, and sometimes it is necessary. To do this, define a dictionary with a pair of empty curly braces, and then add the key-value pairs in line.
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
Copy the code
- When using dictionaries to store user-supplied data or when writing code that automatically generates a large number of key-value pairs, you usually need to define an empty dictionary first.
Modify values in the dictionary
- To modify a value in a dictionary, specify the dictionary name, the key enclosed in square brackets, and the new value associated with that key.
alien_0 = {}
alien_0['color'] = 'green'
print(f"The alien is {alien_0['color']}.")
alien_0['color'] = 'yellow'
print(f"The alien is {alien_0['color']}.")
Copy the code
Delete key-value pairs
- For information that is no longer needed in the dictionary, use
del
Statement removes the corresponding key-value pair completely. - use
del
Statement, you must specify the dictionary name and the key to delete.
alien_0 = {'color': 'green'.'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
Copy the code
A dictionary of similar objects
- In the previous example, the dictionary stored multiple pieces of information for one object (an alien in the game), but you can also use the dictionary to store the same piece of information for many objects.
favorite_language = {
'jen': 'python'.'sarah': 'c'.'edward': 'ruby'.'phil': 'python',}Copy the code
- It’s a good idea to put a comma after the last key-value pair as well, in preparation for adding the key-value pair later on the next line.
- Given the researcher’s name, it’s easy to get his favorite programming language:
favorite_language = {
'jen': 'python'.'sarah': 'c'.'edward': 'ruby'.'phil': 'python',
}
language = favorite_language['sarah'].title()
print(f"Sarah's favorite language is {language}")
Copy the code
useget()
To access the value
- Getting a value of interest from a dictionary using a key placed in square brackets can cause problems: an error occurs if the specified key does not exist.
- But as far as dictionaries are concerned, methods can be used
get()
Avoid this error by returning a default value if the specified key does not exist. - methods
get()
The first argument to specify the key is essential; The second argument is the value to return if the specified key does not exist, which is optional:
alien_0 = {'color': 'green'.'speed': 'slow'}
point_value = alien_0.get('points'.'No point value assigned.')
print(point_value)
Copy the code
- call
get()
If no second argument is specified and the specified key does not exist, Python returns the valueNone
.
Through the dictionary
- Dictionaries can be used to store information in a variety of ways, so there are multiple ways to traverse: you can traverse all of the dictionary’s key-value pairs, or you can traverse just the keys or values.
Iterate over all key-value pairs
- The following dictionary stores the username, first name, and last name of a user:
user_0 = {
'username': 'efermi'.'first': 'enrico'.'last': 'fermi',}Copy the code
- use
for
Loop through the dictionary:
user_0 = {
'username': 'efermi'.'first': 'enrico'.'last': 'fermi',}for key, value in user_0.items():
print(f"\nKey: {key}")
print(f"Value: {value}")
Copy the code
Iterate over all the keys in the dictionary
- Method when a dictionary value is not needed
keys()
Is very useful.
favorite_language = {
'jen': 'python'.'sarah': 'c'.'edward': 'ruby'.'phil': 'python',}for name in favorite_language.keys():
print(name.title())
Copy the code
Traverse all keys in a dictionary in a particular order
- One way to return elements in a particular order is in
for
The loop sorts the returned keys. - To do this, use functions
sorted()
To get the ones in a particular orderA copy of the key list:
favorite_language = {
'jen': 'python'.'sarah': 'c'.'edward': 'ruby'.'phil': 'python',}for name in sorted(favorite_language.keys()):
print(f"{name.title()}, thank you for taking the poll.")
Copy the code
Iterate over all the values in the dictionary
- You can use methods if you are primarily interested in the values contained in the dictionary
values()
To return a list of values without any keys.
favorite_language = {
'jen': 'python'.'sarah': 'c'.'edward': 'ruby'.'phil': 'python',}print("The following languages have been mentioned:")
for language in favorite_language.values():
print(language.title())
Copy the code
- This method extracts all the values in the dictionary, regardless of whether they are duplicated.
- To weed out duplicates, use collections
set
. Each element in the collection must be unique:
favorite_language = {
'jen': 'python'.'sarah': 'c'.'edward': 'ruby'.'phil': 'python',}print("The following languages have been mentioned:")
for language in set(favorite_language.values()):
print(language.title())
Copy the code
- You can create a collection directly with a pair of curly braces where the elements are separated by commas:
languages = {'python'.'ruby'.'python'.'c'}
print(languages)
Copy the code
Collections and dictionaries are easily confused because they are both defined with a pair of curly braces. When there are no key-value pairs inside curly braces, you are most likely defining a collection. Unlike lists and dictionaries, collections do not store elements in a particular order.
nested
- Sometimes, you need to store a series of dictionaries in a list, or a list as a value in a dictionary, which is called nesting.
The dictionary list
- How do you manage swarms of 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)
Copy the code
Store lists in dictionaries
- Sometimes, you need to store a list in a dictionary rather than a dictionary in a list.
- In the following example, two aspects of pizza information are stored: the crust type and the list of ingredients.
pizza = {
'crust': 'thick'.'toppings': ['mushrooms'.'extra cheese'],}print(f"You ordered a {pizza['crust']}-crust pizza "
"with the following toppings:")
for topping in pizza['toppings'] :print("\t" + topping)
Copy the code
- Whenever you need to associate a key to multiple values in a dictionary, you can nest a list in the dictionary.
Store dictionaries in dictionaries
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()}")
Copy the code