Introduction to Python Learning Five: Dictionaries

In this article, we will focus on Python dictionaries that relate related information, and together we will learn how to access and modify the information in the dictionary.The amount of information a dictionary can store is virtually unlimited, so this article shows you how to traverse a dictionary.In addition, you will learn a list of dictionaries to store, a dictionary to store lists, and a dictionary to store dictionaries.
Next, let's start a learning journey!!!

Article Directory

Dictionary Built-in Functions & Method List

The Python dictionary contains the following built-in functions:

Sequence Number function describe
1 cmp(dict1, dict2) Compare two dictionary elements
2 len(dict) Calculates the number of dictionary elements, that is, the total number of keys
3 str(dict) Printable string representation of the output dictionary
4 type(variable) Returns the type of variable entered, or the dictionary type if the variable is a dictionary

The Python dictionary contains the following built-in methods:

Sequence Number function describe
1 dict.clear() Delete all elements from the dictionary
2 dict.copy() Returns a shallow copy of a dictionary
3 dict.fromkeys(seq[, val]) Create a new dictionary with elements in the sequence seq as keys for the dictionary, and val as initial values for all keys in the dictionary
4 dict.get(key, default=None) Returns the value of the specified key, or default if the value is not in the dictionary
5 dict.has_key(key) Returns true if the key is in dictionary dict, false otherwise
6 dict.items() Returns a traversable (key, value) tuple array in a list
7 dict.keys() Returns all keys of a dictionary in a list
8 dict.setdefault(key, default=None) Similar to get(), but if the key does not exist in the dictionary, the key is added and the value set to default
9 dict.update(dict2) Update dictionary dict2 key/value pairs to Dict
10 dict.values() Returns all values in the dictionary as a list
11 pop(key[,default]) Delete the value corresponding to a given key in the dictionary, and the return value is the deleted value.The key value must be given.Otherwise, return the default value.
12 popitem() Returns and deletes the last pair of keys and values in the dictionary.

1 Understand Dictionary

Let's take an example of what a dictionary is:

people_0 = {'first_name':'Qi','last_name':'Zhang','age':18,'city':'Beijing'}#Keep this person's information in the dictionary
print(people_0['first_name'])#Print out one by one
print(people_0['last_name'])
print(people_0['age'])
print(people_0['city'])
#Print Output
//Qi
//Zhang
18
//Beijing

2 Use a dictionary

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 the keys can be numbers, strings, lists, or even dictionaries.In fact, any Python object can be used as a value in a dictionary.In Python, dictionaries are represented by a series of key-value pairs placed in curly brackets {}, as shown in the previous example:

people_0 = {'first_name':'Qi','last_name':'Zhang','age':18,'city':'Beijing'}

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

2.1 Accessing values in a dictionary

Here's an Alien Dictionary with two keys: Color and Points:

alien_0 = {'color':'green','points':5}#Create a dictionary named alien_0
new_points = alien_0['points']#Get the value associated with the key "points" from the dictionary and store it in new_points
print("You just earned "+str(new_points)+" points!")#Converts the obtained key value integer to a string and prints the output
#Print Output
You just earned 5 points!

2.2 Add key-value pairs

A dictionary is a dynamic structure that allows you to add key-value pairs at any time:

alien_0 = {'color':'green','points':5}
print(alien_0)
alien_0['x_position'] = 0#Add aliens'coordinate values and new key-value pairs to the dictionary alien_0
alien_0['y_position'] = 25
print(alien_0)
#Print results
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

In practice, you sometimes need to create an empty dictionary and add key-value pairs one by one.

2.3 Modify values in the dictionary

Modify the key values for the color keys in the Alien Dictionary:

alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'#Change original key value to yellow
print("The alien is now " + alien_0['color'] + ".")
#Print results
The alien is green.
The alien is now yellow.

The next step is to track the position of an alien moving at different speeds. If moving at a slow speed, one position will be shifted, if moving at a moderate speed, two positions will be shifted, if moving at a fast speed, three positions will be shifted, and the new position will be equal to the original position plus an increment.

alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print("Original x-position: " + str(alien_0['x_position']))
# Move Alien Right
# How far an aliens move depends on their current speed
if alien_0['speed'] == 'slow':
    x_increment = 1
elif alien_0['speed'] == 'medium':
    x_increment = 2
else:
# This aliens must be fast
    x_increment = 3
# New location equals old location plus increment
alien_0['x_position'] = alien_0['x_position'] + x_increment
print("New x-position: " + str(alien_0['x_position']))  
#Print results
Original x-position: 0
New x-position: 2

2.4 Delete Key-Value Pairs

For information that is no longer needed in a dictionary, the del statement can be used to completely delete the corresponding key-value pairs, and the name of the dictionary and the key to delete must be specified when using the del statement.

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

2.5 Dictionary of similar objects

In the previous examples, a dictionary is used to store many kinds of information for one object. Next, let's learn to use a dictionary to store the same information for many objects.When you need to define a dictionary with multiple lines, press Enter after entering the left curly bracket, indent four spaces on the next line, specify the first key-value pair, and add a comma after it.When you press Enter again afterwards, the text editor will automatically indent the subsequent key-value pairs with the same indentation as the first key-value pair.
After defining the dictionary, add a right curly brace to the next line of the last key-value pair and indent the four spaces to align them with the keys in the dictionary.Another good practice is to add a comma after the last key-value pair in preparation for adding the key-value pair on the next line.

Programming_vocabulary = {
    'class':'class',
    'abstract':'abstract',
    'access':'access',
    'object':'object',
    'out':'output',
    'run':'Function',
    'print':'Print',
    }
print(Programming_vocabulary)
#Print results
{'class': 'class', 'abstract': 'abstract', 'access': 'access', 'object': 'object', 'out': 'output', 'run': 'Function', 'print': 'Print'}

3 Traverse Dictionary

All key-value pairs can be traversed during traversal, or only keys or values can be traversed.

3.1 Traverse through all key-value pairs (items())

To supplement the previous example, we print out each programming word and its meaning traversally:

Programming_vocabulary = {
    'class':'class',
    'abstract':'abstract',
    'access':'access',
    'object':'object',
    'out':'output',
    'run':'Function',
    'print':'Print',
    }
for voc,meaning in Programming_vocabulary.items():#A for loop is used to iterate through all key-value pairs in the dictionary, with keys stored in the variable voc and values stored in the meaning.Where method items() returns a list of key-value pairs
    print(voc.title()+" : "+meaning)
    #Print results
    Class : class
    Abstract : abstract
    Access : access
    Object : object
    Out : output
    Run : Function
    Print : Print

3.2 Traverse through all keys in the dictionary (keys())

It is necessary to use the method key() to get the keys in a dictionary when the values in the dictionary are not needed.For example, we will print out all the programming languages in the above example:

Programming_vocabulary = {
    'class':'class',
    'abstract':'abstract',
    'access':'access',
    'object':'object',
    'out':'output',
    'run':'Function',
    'print':'Print',
    }
for voc in Programming_vocabulary.keys():#The method keys() takes keys out of the dictionary and stores them in the variable voc, where keys() can actually be omitted
    print(voc.title())
    #Print results
    Class
    Abstract
    Access
    Object
    Out
    Run
    Print

The order returned by key-value pairs is always difficult to predict during traversal. To return a list of keys in a specific order, you need to use the sorted() method.

3.3 Traverse through all the values in the dictionary (values())

If you only want to get a value in the returned result and not any key information, you can do so using the method values(), as in the example above:

Programming_vocabulary = {
    'class':'class',
    'abstract':'abstract',
    'access':'access',
    'object':'object',
    'out':'output',
    'run':'run',
    'print':'print',
    }
for meaning in Programming_vocabulary.values(): #method keys() takes keys out of a dictionary and stores them in a variable voc
    print(meaning)
    #Print results
    class
   abstract
   access
   object
   output
   Function
   Print

It is important to note that if the value you want to print is unique, you need to call set() on the list containing duplicate elements to let Python find the unique elements in the list and use them to create a collection.

4 Nested

Sometimes a dictionary is stored in a list, or a list is stored as a dictionary, which is called nesting.

4.1 Dictionary List

We use range() to generate 30 aliens:

# Create an empty list to store aliens
aliens = []
# Create 30 green aliens
for alien_number in range(30):#Cycle 30 times, once each, to create an aliens.
    new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
    aliens.append(new_alien)#And append each newly created aliens to the end of the aliens list
# Show the first five aliens
for alien in aliens[:5]:#Print the first five aliens using the slices you learned earlier
    print(alien)
print("...")
# Show how many aliens were created
print("Total number of aliens: " + str(len(aliens)))#Use len() to calculate the length of the list
#Print results
{'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

Each of the 30 aliens created here is independent and can be modified if we take the first five aliens
Change the color to yellow, the number of points to 10, and the speed to fast.

# Create an empty list to store aliens
aliens = []
# Create 30 green aliens
for alien_number in range(30):#Cycle 30 times, once each, to create an aliens.
    new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
    aliens.append(new_alien)#And append each newly created aliens to the end of the aliens list
for alien in aliens[0:5]:    
    if alien['color'] == 'green':   #if statement to ensure only green aliens are modified 
        alien['color'] = 'yellow'        
        alien['speed'] = 'fast'        
        alien['points'] = 10
# Show the first five aliens 
for alien in aliens[0:6]:    
    print(alien) 
print("...")
#Print results
{'color': 'yellow', 'points': 10, 'speed': 'fast'}
{'color': 'yellow', 'points': 10, 'speed': 'fast'}
{'color': 'yellow', 'points': 10, 'speed': 'fast'}
{'color': 'yellow', 'points': 10, 'speed': 'fast'}
{'color': 'yellow', 'points': 10, 'speed': 'fast'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...  

4.2 Store lists in dictionaries

Whenever you need to associate a key to multiple values in a dictionary, you can nest a list in the dictionary.
Example: What you like: Create a dictionary named favorite_places.In this dictionary, the names of three people are used as keys; for each of them, one or three places he likes are stored.Walk through the dictionary and print out each person's name and his or her favorite place.

favorite_places = {
    'lily' : ['West Lake','South Lake','Tiananmen'],
    'lilian' : ['Qinghai','Summer Palace','Du Fu Cottage'],
    'wangmin' : ['Water Construction','Hangzhou','Nanjing'],
    'bily' : ['U.S.A','Hunan','Penghu Bay'],
    }
for name, places in favorite_places.items(): #Traverse Dictionary     
    print("\n" + name.title() + "'s favorite places are:")     
    for place in places : #Traversing place names         
        print("\t" + place.title())

4.3 Store Dictionary in Dictionary China

For example, if you have multiple site users, each with a unique user name, you can use the user name as the key in a dictionary, then store each user's information in a dictionary and use that dictionary as the value associated with the user name.In the following programs, for each user, we store three pieces of information: first name, last name, and residence. To access this information, we iterate through all user names and access the information dictionary associated with each user name:
We first defined a dictionary named users that contains two keys: user name'aeinstein'and'mcurie'; the values associated with each key are a dictionary that contains the user's name, first name, and residence.

 users = {      
     'aeinstein': {          
          'first': 'albert',          
          'last': 'einstein',          
          'location': 'princeton',          
          },
      'mcurie': {          
          'first': 'marie',          
          'last': 'curie',          
          'location': 'paris',          
          },
      }
for username, user_info in users.items():#We iterate through the dictionary users and let Python store each key in turn in the variable username.
                                         #In turn, the dictionary associated with the current key is stored in the variable user_info.     
    print("\nUsername: " + username)  #Print username    
    full_name = user_info['first'] + " " + user_info['last']# The variable user_info contains a dictionary of user information.
                                                            #The dictionary contains three keys:'first','last'and'location'      
    location = user_info['location']
    print("\tFull name: " + full_name.title())      
    print("\tLocation: " + location.title())
#Print Output
Username: aeinstein
	Full name: Albert Einstein
	Location: Princeton

Username: mcurie
	Full name: Marie Curie
	Location: Paris

At the end of this article, thank you for reading, followed by an update of the Python introductory learning knowledge, please read, thank you!!!

Reference Blog: https://blog.csdn.net/qq_40265974/article/details/103912304
Reference book: Python Programming From Getting Started to Practice

Published 8 original articles. Praise 0. Visits 1198
Private letter follow

Tags: Python Programming

Posted on Fri, 14 Feb 2020 22:09:42 -0500 by matt121400