Introduction to Python dictionary

1, Form:

rivers = {
    "Níluóhé": "Egypt",
    "Yangtze River": "China",
    "Yellow River": "China",
    "Mississippi River": "USA",
    "Ganges":"India"
    }

2, Use dictionary

(1) Accessing values in the dictionary

For example, for dictionaries:

color_like = {"boy": "blue", "girl": "pink"}

It is required to output the value corresponding to the second key in the dictionary:
The code is as follows:

print(color_like["girl"]) # Output pin

The value form in the output dictionary is: dictionary name [key name]
Require value to be substituted into string:
The code is as follows:

color = color_like["girl"]
print(f"Girls' favorite color is {color}")

Output:

Girls' favorite color is pink

(2) Add key value pairs to the dictionary

A dictionary is a dynamic structure in which key value pairs can be added at any time

Still use the above Dictionary:

color_like = {"boy": "blue", "girl": "pink"}

Require a key value pair to be added to the dictionary:
The code is as follows:

color_like = {"boy": "blue", "girl": "pink"}
print(color_like)
color_like["Soldier"] = "green"
print(color_like)

Output:

{'boy': 'blue', 'girl': 'pink'}
{'boy': 'blue', 'girl': 'pink', 'Soldier': 'green'}

Clearly! A new key value pair has been implanted in the dictionary

(3) Modify values in the dictionary

Still the above Dictionary:

color_like = {"boy": "blue", "girl": "pink"}

It is required to change the value corresponding to the first key from "blue" to "black":
The code is as follows:

color_like["boy"] = "black"  #This is similar to adding values
print(color_like)

Output:

{'boy': 'black', 'girl': 'pink'}

It can be seen that "blue" has been changed to "black"

(4) Delete key value pair

Use the del statement to completely delete the corresponding key value pairs
Still use the above Dictionary:

color_like = {"boy": "blue", "girl": "pink"}

It is required to delete the key value pair "boy": "blue":

The code is as follows:

print(color_like)
del color_like["boy"]
print(color_like)

Output:

{'boy': 'blue', 'girl': 'pink'}
{'girl': 'pink'}

Through comparison, it can be seen that the key value pair of "boy" has been deleted in the dictionary

(5) Use get() to access the values in the dictionary

The advantage of get() is that when a key in the dictionary is called with a conventional method, an error will occur if the specified key does not exist -- traceback is displayed, indicating the existence of keyError
Still use the dictionary:

{'boy': 'blue', 'girl': 'pink'}

If you print a non-existent key value at this time, that is:

print(color_like["young"])

Then the system will report an error:

Traceback (most recent call last):
  File "E:/pycharm code/text.py", line 523, in <module>
    print(color_like["young"])
KeyError: 'young'
# Indicates that there is a KeyError

If you print out with get(), that is:

color_like = {"boy": "blue", "girl": "pink"}
a = color_like.get("young", "red")
print(a)

The structure of get() is: dictionary name. get(A,B)
"young" is the first parameter (A) used to specify the key - essential
"red" is the second parameter (B), which is used to specify the value to be returned when the key does not exist - which can be understood as the value corresponding to the non-existent key

Output:

red  # Return parameter B (red)

In addition

In general, you can also use get() to print out key values
The code is as follows:

color_like = {"boy": "blue", "girl": "pink"}
a = color_like.get("boy")
print(a)

Output:

blue

3, Traversal dictionary

With the help of the for loop, you can traverse the keys, values, keys and values in the dictionary

(1) Traverse all key value pairs

Here, each key and its corresponding value are printed with the help of. item() as a suffix

It is required to print out the dictionary keys and corresponding values at the same time:
The code is as follows:

my_favorite = {
    "food": "bread",
    "clothes": "Hoodie",
    "name": "Steven",
    "city": "HangZhou"
}
for a, b in my_favorite.items():  # item indicates that the key and value are printed out
    # a. B is a variable that stores keys and values
    print(f"my favorite {a} is {b}!")

Output:

my favorite food is bread!
my favorite clothes is Hoodie!
my favorite name is Steven!
my favorite city is HangZhou!

(2) Traverse all keys in the dictionary

Here, each key is printed out with. keys() as a suffix

Still use the above Dictionary:

my_favorite = {
    "food": "bread",
    "clothes": "Hoodie",
    "name": "Steven",
    "city": "HangZhou"
}

It is required to print out the keys in the dictionary in turn:
The code is as follows:

for a in my_favorite.keys(): 
    print(f"a:{a}")

Output:

a:food
a:clothes
a:name
a:city

(3) Traverse all values in the dictionary

Here, each value is printed out with. values() as a suffix

It is required to print out the values in the dictionary in turn:
The code is as follows:

for b in my_favorite.values():  
    print(f"b:{b}")

Output:

b:bread
b:Hoodie
b:Steven
b:HangZhou

4, Nesting

(1) Nested dictionary in list

For example, the following is to create a list of three dictionaries
The code is as follows:

our_favorite = ["Tom", "Steven", "Jim"]
Tom_favorite = {"food": "beef", "color": "red"}
Steven_favotite = {"food": "sandwich", "color": "blue"}
Jim_favorite = {"food": "bread", "color": "black"}
for somebody_favorite in our_favorite:
    # Traverse the list and print out each dictionary a
    print(somebody_favorite)

(2) Store list in dictionary

The following is a list embedded in the dictionary, where the whole list is used as a key value
The code is as follows:

pizza = {
    "crust": "thick",
    "topping": ["mushrooms", "extra cheese"]
}

(3) Store dictionary in dictionary

The following is the embedded dictionary in the dictionary. Each embedded dictionary is used as a key value here
The code is as follows:

pizza_color = {
    "seasoning": {"butter": "yello",
                  "pepper": "black",
                  "ketchup": "red"
                  },
    "tableware": {"plate": "white",
                  "fork": "silver",
                  "tablecloth": "Orange"
                  }
}

5, Summary

The above is a summary of the basic knowledge of the dictionary

Keywords: Python Pycharm

Added by andrewburgess on Wed, 24 Nov 2021 06:33:26 +0200