Python learning record Chapter 6 dictionary

Posted by majik_sheff on Fri, 18 Feb 2022 16:25:08 +0100

Chapter VI dictionary

6.1 a simple dictionary

Let's look at a game containing aliens. These aliens have different colors and scores. Here is a simple dictionary that stores information about specific Aliens:

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

print(alien_0['color'])
print(alien_0['points'])

Dictionary alien_0 stores alien colors and scores. The last two lines of code access and display this information:

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 relevant value. 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, the dictionary is represented by a series of key value pairs placed in curly brackets {}, as shown in the previous example:

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.

The simplest dictionary has only one key value pair, such as the modified dictionary alien_0 shows:

alien_0 = {'color':'green'}

The dictionary stores a piece of information about alien, specifically the alien's color. In this dictionary, the string 'color' is a key, and its associated value is' green '.

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

The dictionary can contain any number of key value pairs. For example, here is the original dictionary alien_0, which contains two key value pairs:

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

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

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

new_points = alien_0['points']
print(f"You just earned {new_points} points!")

Output:

You just earned 5 points!

6.2.2 adding key value pairs

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.

Here's the dictionary, alien_0 to add two information: the x-coordinate and y-coordinate of the alien, so that we can display the alien in a specific position on the screen. We put the alien on the left edge of the screen, 25 pixels from the top of the screen. Since the origin of the screen coordinate system is usually in the upper left corner, to place the alien on the left edge of the screen, set the X coordinate to 0; To place the alien 25 pixels from the top of the screen, set the Y coordinate to 25, as follows:

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

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

Output:

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

The final version of this dictionary contains four key value pairs.

6.2.3 create an empty dictionary first

Adding key value pairs to an empty dictionary is sometimes convenient and sometimes necessary. To do this, first define a dictionary with a pair of empty curly braces, and then add each key value pair separately. As follows:

alien_0 = {}

alien_0['color'] = 'green'
alien_0['points'] = 5

print(alien_0)

Output:

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

When using a dictionary to store user provided data or writing code that can automatically generate a large number of key value pairs, it is usually necessary to define an empty dictionary first.

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, as the game progresses, you need to change an alien from green to yellow:

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

alien_0['color'] = 'yellow'
print(alien_0)

Output:

{'color': 'green'}
{'color': 'yellow'}

Let's take a more interesting example, tracking the position of an alien who can move at different speeds. To this end, we will store the alien's current speed and determine how far the alien will move to the right:

alien_0 = {'x_position':0,'y_position':25,'speed':'medium'}
print(f"Original x-position:{alien_0['x_position']}")

#Move aliens to the right
#Determine how far the alien moves to the right according to the current speed
if alien_0['speed'] == 'slow':
    x_increment = 1
elif alien_0['speed'] == 'medium':
    x_increment = 2
else:
    #This alien must be moving faster
    x_increment = 3
#The new position is the old position plus the moving distance
alien_0['x_position'] += x_increment

print(f"New x-position: {alien_0['x_position']}")

Output:

Original x-position:0
New x-position: 2

6.2.5 deleting key value pairs

For unnecessary information in the dictionary, you can use del statement to completely delete the corresponding key value pairs. When using a dictionary statement, you must specify the dictionary name and the key to be deleted.

For example, the following code from dictionary alien_ Delete the key 'points' and its value from 0:

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

del alien_0['points']
print(alien_0)

Output:

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

Note: deleted key values will disappear forever

6.2.6 dictionary composed of similar objects

In the previous example, the dictionary stores multiple information of an object, but you can also use the dictionary to store the same information of many objects. For example, if you want to survey many people and ask them about their favorite programming language, you can use a dictionary to store the results of this simple survey, as follows:

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

We put a larger dictionary in multiple lines. Each key is a respondent's name, and each value is the respondent's favorite language. To confirm that you need to use multiple lines to define the dictionary, press enter after entering the left curly bracket. Indent the next line with four spaces, specify the first key value pair, and add a comma after it. When you press enter again, the editor will automatically indent the subsequent key value pairs by the same amount as the first key value.

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

Note: for long lists and dictionaries, most editors provide the ability to format 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.

Given the respondent's name, you can easily learn his favorite language using this dictionary:

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.

6.2.7 using get() to access values

Using the key enclosed in square brackets to get the value of interest from the dictionary can cause problems: an error occurs if the specified key does not exist.

If you ask for an alien's score and the alien doesn't have a score, what's the result?

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

This will cause python to display traceback indicating that there is a KeyError:

Traceback (most recent call last):
  File "D:\major\machine learning\Assignment 4\untitled0.py", line 2, in <module>
    print(alien_0['points'])
KeyError: 'points'

Chapter 10 details how to handle similar errors, but in the case of dictionaries, you can avoid such errors by using the method get() to return a default value when the specified key does not exist.

The first parameter of the method get() is used to specify the key, which is essential; The second parameter is the value to be returned when the specified key does not exist. It is optional:

alien_0 = {'color':'green','speed':'slow'}

point_value = alien_0.get('points','No point value assigned.')
print(point_value)

If there is a key 'points' in the dictionary, the value associated with it will be obtained; If not, the specified default value is obtained. Although there is no key 'points' here, you will get a clear message without causing an error:

No point value assigned.

If the specified key may not exist, consider using the method get() instead of the square bracket notation.

Note: when calling get(), if the second parameter is not specified and the specified key does not exist, python will return the value none. This special value indicates that there is no corresponding value. None is not an error, but a special value indicating that the required value does not exist. Its other uses will be described in detail in Chapter 8.

6.3 traversal dictionary

A python dictionary may contain several 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: you can traverse all key value pairs of the dictionary, or you can traverse only keys or values.

6.3.1 traverse all key value pairs

Before exploring various traversal methods, let's look at a new dictionary, which is used to store information about website users. The following dictionary stores the user name, first name and last name of a user:

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

Using the knowledge introduced earlier in this chapter, you can access user_0, but what if you want to know all the information in the user's dictionary? You can use the for loop to traverse 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}")

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

for key,value 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. Next, the for loop assigns each key value pair to the specified two variables in turn. In this example, these two variables are used to print each key and its associated value. The first function call "\ n" in print() ensures that an empty line is inserted before each key value pair is output:

Key:username
Value:efermi

Key:first
Value:enrico

Key:last
Value:fermi

The example favorite in section 6.2.6_ In languages, dictionaries store the same information of different people. For dictionaries like this, it is appropriate to traverse all key value pairs. If you traverse the dictionary favorite_languages, you will get the name of each of them and your favorite programming language. Since the keys in the dictionary are people's names and the values are languages, the variables name and language are used in the loop instead of key and value. This makes it easier to understand the role of circulation:

favorite_languages = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
for name,language in favorite_languages.items():
    print(f"{name.title()}'s favorite language is {language.title()}.")

Output:

Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Python.

6.3.2 traverse all keys in the dictionary

The method key() is useful when you do not need to use the values in the dictionary. Let's traverse the dictionary favorite_languages and print out the name of each respondent:

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

for name in favorite_languages.keys():
    print(name.title())

Output:

Jen
Sarah
Edward
Phil

When traversing the dictionary, all keys are traversed by default. Therefore, if the above code is:

for name in favorite_languages.keys():

Replace with:

for name in favorite_languages:

The output will remain unchanged.

Using the method key() explicitly can make the code easier to understand. You can choose to do so or omit it.

In this loop, the current key can be used to access the value associated with it. Now print two messages to indicate the language your two friends like. Traverse the names in the dictionary as before, but when the name is the name of the specified friend, print a message indicating his preferred language:

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

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}!")

Everyone's name will be printed, but only special messages will be printed for friends:

Hi Jen.
Hi Sarah.
	Sarah,I see you love C!
Hi Edward.
Hi Phil.
	Phil,I see you love Python!

Determine whether a method is acceptable to a person. The following code determines whether Erin was investigated:

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

if 'erin' not in favorite_languages.keys():
    print("Erin,please take our poll!")

Output:

Erin,please take our poll!

The method keys() is not restricted to traversal: in fact, it returns a list containing all the keys in the dictionary. Therefore, the above code just verifies whether 'erin' is in this list.

6.3.3 traverse all keys in the dictionary in a specific order

From Python 3 From 7, the elements in the dictionary will be returned in the order of insertion when traversing the dictionary. However, in some cases, you may have to traverse the dictionary in a different order.

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(f"{name.title()},thank you for taking the poll!")

This for statement is similar to other for statements, except for the method dictionary The result of keys() calls the function sorted(). This lets python list all the keys in the dictionary and sort the list before traversing. 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 primarily interested in the values contained in the dictionary, you can use the method values() to return a list of values without any keys. For example, suppose we want to get a list that contains only the various languages selected by the respondent, not the respondent's name, we can do this:

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())

This for statement extracts each value in the dictionary and assigns it to the variable language in turn. By printing these values, a list containing the language selected by the respondents is obtained:

The following languages have been mentioned:
Python
C
Ruby
Python

This method extracts all the values in the dictionary without considering whether they are repeated or not. This may not be a problem when there are few values involved, but if there are many respondents, the final list may contain a large number of duplicates. To weed out duplicates, use a set. Each element in the collection 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())

By calling set() on the list containing elements, python can find the unique elements in the list and use them to create a collection. The above code uses set() to extract favorite_ languages. Different languages in values().

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

The following languages have been mentioned:
C
Ruby
Python

Note: you can use a pair of curly braces to create a collection directly and separate the elements with commas:
>>>languages = {'python','ruby','python','c'}
>>>languages
{'ruby','python','c'}
Collections and dictionaries are easily confused because they are defined by a pair of curly braces. When there are no key value pairs in curly braces, it is likely that a collection is defined. Unlike lists and dictionaries, collections do not store elements in a specific order.

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

Dictionary alien_0 contains all kinds of information about an alien, but it can't store the information of a second alien, let alone all the information of aliens on the screen. How to manage groups of aliens? One way is to create a list of aliens, in which each alien is a dictionary containing all kinds of information about aliens. For example, the following code creates a list of three 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)

First, create three dictionaries, each of which represents an alien. These dictionaries are then stored in a list called aliases. Finally, traverse the list and print out each Alien:

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

A more realistic scenario is that there are more than three aliens, and each alien is automatically generated using code. In the following example, 30 aliens are generated using range():

# Create an empty list for storing aliens
aliens = []

# Create 30 green aliens
for alien_number in range(30):
    new_alien = {'color': 'green', 'points': '5','speed':'slow'}
    aliens.append(new_alien)

#Show the first five aliens
for alien in aliens[:5]:
    print(alien)
print('...')

#Shows how many aliens were created
print(f"Total number of aliens:{len(aliens)}")

Output:

{'color': 'green', 'points': '5', 'speed': 'slow'}
{'color': 'green', 'points': '5', 'speed': 'slow'}
{'color': 'green', 'points': '5', 'speed': 'slow'}
{'color': 'green', 'points': '5', 'speed': 'slow'}
{'color': 'green', 'points': '5', 'speed': 'slow'}
...
Total number of aliens:30

These aliens have the same characteristics, but in python's view, each alien is independent, which allows us to modify each alien independently.

Under what circumstances do you need groups of aliens? Imagine that some aliens may change color and speed up as the game goes on. If necessary, you can use the for loop and if statement to modify the color of some aliens. For example, to change the first three aliens to yellow, medium speed and 10 points, you can do this:

# Create an empty list for storing aliens
aliens = []

# Create 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 five aliens
for alien in aliens[:5]:
    print(alien)
print('...')

In order to modify the first three aliens, we traverse a slice containing only these aliens. At present, all aliens are green, but this is not always the case, so write an if statement to ensure that only green aliens are modified. if the alien is green, modify its color, speed and score, and the output is as follows:

{'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'}
...

This cycle can be further expanded by adding an elif code block to it. The Yellow alien is changed into a red alien with fast moving speed and a value of 15 points, as follows (only the cycle is listed here, not the whole program):

for alien in aliens[: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

It is often necessary to include a large number of dictionaries in the list, and each dictionary contains a lot of information about a specific object. For example, you may need to create a dictionary for each user of the website (as in user in section 6.3.1) and store these dictionaries in a list called user. In this list, all dictionaries have the same structure, so you can traverse the list and process each dictionary in the same way.

6.4.2 storing lists in dictionaries

Sometimes you need to store a list in a dictionary instead of a dictionary in a list. For example, how would you describe a customer's pizza? If the list is used, only the pizza ingredients to be added can be stored; But if you use a dictionary, you can include not only a list of ingredients, but also other descriptions of pizza.

In the following example, two aspects of pizza are stored: skin type and ingredient list. The ingredient list is a value associated with the key 'toppings'. To access the list, we use the dictionary name and the key 'toppings', just as we access other values in the dictionary. This will return a list of ingredients instead of a single value:

# Store information about the pizza you ordered
pizza = {
    'crust':'thick',
    'toppings':['mushrooms','extra cheese'],
    }

# Overview of pizza ordered
print(f"You ordered a {pizza['crust']}-crust pizza "
    "with the following toppings:")

for topping in pizza['toppings']:
    print("\t"+topping)

First, create a dictionary that stores information about the pizza the customer ordered. In this dictionary, a key is' crust 'and its associated value is' thick'; The next key is' toppings', and the value associated with it is a list that stores all the ingredients required by the customer. If the string in the calling function print() is very long, you can branch in the appropriate place. Just put quotation marks at the end of each line, and put quotation marks and indent at the beginning of all lines except the first line. In this way, python will automatically merge all strings within parentheses. To print ingredients, write a for loop. To access the ingredient list, use the key 'toppings'.

Output:

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

Whenever you need to associate a key to multiple values in the dictionary, you can nest a list in the dictionary. In the example of preferred programming languages earlier in this chapter, if each person's answer is stored in a list, respondents can choose multiple preferred languages. In this case, when we traverse the dictionary, each respondent is associated with a language list, not a language; Therefore, in the for loop traversing the dictionary, we need to use another for loop to traverse the language list associated with the respondent:

favorite_languages = {
    'jen':['python','ruby'],
    'sarah':['c'],
    'edward':['ruby','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()}")

As you can see, the values associated with each name are now a list. Please note that some people like only one language, while others have multiple languages. When traversing the dictionary, use the variable languages to store references to each value in the dictionary in turn, because we know that these values are lists. In the main loop of traversing the dictionary, another for loop is used to traverse everyone's favorite language list. Now, everyone can list how many languages they like:

Jen's favorite languages are:
	Python
	Ruby

Sarah's favorite languages are:
	C

Edward's favorite languages are:
	Ruby
	Go

Phil's favorite languages are:
	Python
	Haskell

In order to further improve the program, an if statement can be added at the beginning of the for loop traversing the dictionary to determine whether the current respondents like multiple languages by looking at the value of len(languages). if he likes multiple languages, display the output as before; if there is only one, change the wording.

favorite_languages = {
    'jen':['python','ruby'],
    'sarah':['c'],
    'edward':['ruby','go'],
    'phil':['python','haskell'],
    }

for name,languages in favorite_languages.items():
    if len(languages) == 1:
        print(f"\n{name.title()}'s favorite languages is:")
        for language in languages:
            print(f"\t{language.title()}")
    else:
         print(f"\n{name.title()}'s favorite languages are:")
         for language in languages:
            print(f"\t{language.title()}")

Note: lists and dictionaries should not have too many nesting levels. If there are many more levels of nesting than in the previous example, there is likely to be a simpler solution.

6.4.3 store dictionary in dictionary

You can nest dictionaries in dictionaries, but when you do, your code can quickly become complex. For example, if you have multiple website users, each with a unique user name, you can use the user name as a key in the dictionary, then store each user's information in a dictionary and use the dictionary as the value associated with the user name. In the following program, three items of information for each user are stored: first name, last name and place of residence. To access this information, we traverse all user names and access the information dictionary associated with each user name:

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()}")

First, define a dictionary named users, which contains two keys: the user name 'aeinstein' and 'mcurie'. The value associated with each key is a dictionary that contains the user's first name, last name, and place of residence. First traverse the dictionary users, let python assign each key to the traversal username in turn, and assign the dictionary associated with the current key to the variable user in turn_ info. Inside the loop, print out the user name.

Then start accessing the internal dictionary. Variable user_info contains a user information dictionary, which contains three keys: 'first', 'last' and 'location'. For each user, 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 that the dictionary representing each user has the same structure. Although python does not have such a requirement, it makes nested dictionaries easier to handle. If the dictionary representing each user contains different keys, the code inside the for loop will be more complex.