Learning notes of Python: Programming: from introduction to practice_ Chapter 6 dictionary

Posted by kankohi on Wed, 02 Feb 2022 16:00:46 +0100

Chapter 6 dictionary

6.1 a simple dictionary

alien_0 = {'color': 'green', 'points': 5} 
print(alien_0['color']) 
print(alien_0['points']) 

Dictionary alien_0 stores alien colors and points. Use two print statements to access and print this information, as follows:

green 
5 

6.2 using dictionaries

In Python, a dictionary is a series of key value pairs. Each key is associated with a value, and you can use the key to access the value associated with it. The values associated with keys can be numbers, strings, lists, and even dictionaries. In fact, any Python object can be used as a value in the dictionary.

In Python, dictionaries are represented by a series of key value pairs placed in curly braces {}.

alien_0 = {'color': 'green', 'points': 5}

Key value pairs are two associated values. When you specify a key, Python returns the value associated with it. Keys and values are separated by colons, and key value pairs are separated by commas. In the dictionary, you can store as many key value pairs as you want.

6.2.1 accessing values in the dictionary

To get the value associated with the key, specify the dictionary name and the key in square brackets, as follows:

alien_0 = {'color': 'green'} 
print(alien_0['color']) 

This will return the dictionary alien_ Value associated with key 'color' in 0:

green

Now you can visit alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien alien_0's color and number of points. If the player shoots the alien, you can use the following code to determine how many points the player should get:

alien_0 = {'color': 'green', 'points': 5} 

new_points = alien_0['points'] 
print("You just earned " + str(new_points) + " points!") 

The above code first defines a dictionary, then obtains the value associated with the key 'points' from the dictionary, and stores the value in the variable new_points. Next, convert this integer to a string and print a message indicating how many points the player has obtained:

You just earned 5 points! 

6.2.2 add key value pair

A dictionary is a dynamic structure in 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.

alien_0 = {'color': 'green', 'points': 5} 
print(alien_0) 

alien_0['x_position'] = 0 
alien_0['y_position'] = 25 
print(alien_0)

When printing the modified dictionary, you will see these two new key value pairs:

{'color': 'green', 'points': 5} 
{'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0} 

Note: the arrangement order of key value pairs is different from the addition order. Python does not care about the order in which key value pairs are added, but only about the relationship between keys and values

6.2.3 create an empty dictionary first

Sometimes it's convenient to add key value pairs to an empty dictionary, and sometimes you have to. To do this, first define a dictionary with a pair of empty curly braces, and then add each key value pair separately.

alien_0 = {} 

alien_0['color'] = 'green' 
alien_0['points'] = 5 
print(alien_0) 

Here we first define the empty dictionary alien_0, and then add colors and points to get the dictionary that the previous example has been using:

{'color': 'green', 'points': 5} 

6.2.4 modify the value 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 the key. For example, suppose you need to change an alien from green to yellow as the game goes on:

alien_0 = {'color': 'green'} 
print("The alien is " + alien_0['color'] + ".") 

alien_0['color'] = 'yellow' 
print("The alien is now " + alien_0['color'] + ".")

The output shows that the alien did change from green to yellow:

The alien is green. 
The alien is now yellow.

6.2.5 delete key value pair

For information that is no longer needed in the dictionary, you can use the del statement to completely delete the corresponding key value pair. When using the 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)

The output indicates that the key 'points' and its value 5 have been deleted from the dictionary, but other key value pairs are not affected:

{'color': 'green', 'points': 5} 
{'color': 'green'} 

Note: deleted key value pairs disappear forever.

6.2.6 dictionary composed of similar objects

In the previous example, the dictionary stores a variety of information about an object (an alien in the game), but you can also use the dictionary to store the same information about many objects.

favorite_languages = { 
	'jen': 'python', 
	'sarah': 'c', 
	'edward': 'ruby', 
	'phil': 'python', 
 	}

After defining the dictionary, add a closing curly bracket on the next line of the last key value pair and indent four spaces to align it with the keys in the dictionary. Another good practice is to add a comma after the last key value pair to prepare for adding key value pairs on the next line in the future.

Note: for long lists and dictionaries, most editors have the ability to format them in a similar way. There are other possible formatting options for longer dictionaries, so you may see slightly different formatting options in your editor or other source code.

6.3 traversal dictionary

A Python dictionary may contain only a few key value pairs or millions of key value pairs. Since dictionaries may contain a large amount of data, Python supports traversal of dictionaries. Dictionaries can be used to store information in a variety of ways, so there are many ways to traverse the dictionary: you can traverse all key value pairs, keys, or values of the dictionary.

6.3.1 traverse all key value pairs

user_0 = { 
	'username': 'efermi', 
	'first': 'enrico', 
	'last': 'fermi', 
	}

You can use a for loop to traverse the dictionary:

user_0 = { 
	'username': 'efermi', 
	'first': 'enrico', 
	'last': 'fermi', 
	} 
for key, value in user_0.items(): 
	print("\nKey: " + key) 
	print("Value: " + value) 

To write a for loop that traverses the dictionary, declare two variables that store the keys and values in a key value pair. You can use any name for these two variables. The following code uses simple variable names, which is completely feasible:

for k, v in user_0.items() 

The second part of the for statement contains the dictionary name and the method items(), which returns a list of key value pairs.

Key: last 
Value: fermi
 
Key: first 
Value: enrico 

Key: username 
Value: efermi 

Note: even when traversing the dictionary, the return order of key value pairs is different from the storage order. Python doesn't care about the storage order of key value pairs, but only tracks the correlation between keys and values.

6.3.2 traverse all keys in the dictionary

The method keys() is useful when you don't need to use the values in the dictionary.

favorite_languages = { 
 	'jen': 'python', 
 	'sarah': 'c', 
 	'edward': 'ruby', 
 	'phil': 'python', 
 	}
 
for name in favorite_languages.keys(): 
	print(name.title())

The name of each respondent is listed:

Jen 
Sarah 
Phil 
Edward 

When traversing the dictionary, all keys will be traversed by default. Therefore, if the for name in favor in the above code is_ languages. Keys(): replace with for name in favor_ Languages:, the output will remain unchanged.

If using the method keys() explicitly makes the code easier to understand, you can choose to do so, but you can omit it if you like.

6.3.3 traverse all keys in the dictionary in order

Dictionaries always explicitly record the relationship between keys and values, but when retrieving dictionary elements, the acquisition order is unpredictable. This is not a problem, because usually all you want is to get the correct value associated with the key.
One way to return elements in a specific order is to sort the returned keys in the for loop. To do this, you can use the function sorted() to get a copy of the list of keys in a specific order:

favorite_languages = { 
	'jen': 'python', 
	'sarah': 'c', 
	'edward': 'ruby', 
	'phil': 'python', 
	} 
	
for name in sorted(favorite_languages.keys()): 
	print(name.title() + ", thank you for taking the poll.") 

The output shows that the names of all respondents are displayed in order:

Edward, thank you for taking the poll. 
Jen, thank you for taking the poll. 
Phil, thank you for taking the poll. 
Sarah, thank you for taking the poll.

6.3.4 traverse all values in the dictionary

If you are mainly interested in the values contained in the dictionary, you can use the method values(), which returns a list of values without any keys.

favorite_languages = { 
 	'jen': 'python', 
 	'sarah': 'c', 
 	'edward': 'ruby', 
 	'phil': 'python',
	}

By printing these values, you get a list of the various languages selected by the respondents:

The following languages have been mentioned: 
Python 
C 
Python 
Ruby 

To weed out duplicates, use a set. A collection is similar to a list, but each element must be unique:

favorite_languages = { 
	'jen': 'python', 
	'sarah': 'c', 
	'edward': 'ruby', 
	'phil': 'python', 
 	} 
 	
print("The following languages have been mentioned:") 
for language in set(favorite_languages.values()): 
	print(language.title())

The result is a non repeating list of all the languages mentioned by the respondents:

The following languages have been mentioned: 
Python 
C 
Ruby

6.4 nesting

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. You can nest dictionaries in lists, lists in dictionaries, or even dictionaries in dictionaries.

6.4.1 dictionary list

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)

We traverse the list and print out each Alien:

{'color': 'green', 'points': 5} 
{'color': 'yellow', 'points': 10} 
{'color': 'red', 'points': 15}

6.4.2 storing lists in dictionaries

Sometimes you need to store a list in a dictionary instead of a dictionary in a list.

# Store information about the pizza you ordered
pizza = { 
	'crust': 'thick', 
	'toppings': ['mushrooms', 'extra cheese'], 
	} 
	
# Overview of pizza ordered
print("You ordered a " + pizza['crust'] + "-crust pizza " + 
	 "with the following toppings:") 
	 
for topping in pizza['toppings']: 
	print("\t" + topping)

The following output outlines the pizza to be made:

You ordered a thick-crust pizza with the following toppings: 
	mushrooms 
	extra cheese

Note: lists and dictionaries should not have too many nesting levels.

6.4.3 store dictionary in dictionary

You can nest dictionaries in dictionaries, but when you do, your code can quickly become complex.

users = { 
 	'aeinstein': { 
 		'first': 'albert', 
	 	'last': 'einstein', 
 		'location': 'princeton', 
 		},
  
 	'mcurie': { 
 		'first': 'marie', 
 		'last': 'curie', 
 		'location': 'paris', 
 		},
  
 } 
for username, user_info in users.items(): 
	print("\nUsername: " + username) 
	full_name = user_info['first'] + " " + user_info['last'] 
 	location = user_info['location'] 
 	
	print("\tFull name: " + full_name.title()) 
	print("\tLocation: " + location.title())

For each user, we use these keys to generate a neat name and place of residence, and then print brief information about the user:

Username: aeinstein 
	Full name: Albert Einstein 
	Location: Princeton 
 
Username: mcurie 
	Full name: Marie Curie 
	Location: Paris 

Note: the structure of each user's dictionary is the same. Although Python does not have such requirements, it makes it easier to handle nested dictionaries. If the dictionary representing each user contains different keys, the code inside the for loop will be more complex.

6.5 summary

In this chapter, you learned how to define a dictionary and how to use the information stored in the dictionary; How to access and modify the elements in the dictionary and how to traverse all the information in the dictionary; How to traverse all key value pairs, all keys and all values in the dictionary; How to nest dictionaries in lists, nested lists in dictionaries, and nested dictionaries in dictionaries.