<> How do I look it up in the dictionary ,Python How to use a dictionary

You've learned lists and tuples , Then these two are arranged in order , So you can use the index to get the value , What this blog wants to learn is a dictionary , As can be seen from the above , The dictionary can't get the value according to the index , Just out of order , Non sequential data structure .

<>1 . Basic operation of dictionary

<>1.1 Definition of dictionary

A dictionary can be regarded as a list data structure , It is also a container that can hold many other data types , But the elements in the dictionary use “ key - value ” To represent , and “ key - value ”
Appear in pairs , The relationship between keys and values can be described as , Value by key ( This is the core concept of the dictionary , It's like looking up a dictionary through a radical ).

The syntax format of the dictionary is as follows :
# my_dict Is a variable name my_dict = { key 1: value 1, key 2: value 2......}
The dictionary value is the value in the above format value 1, value 2 Can be numeric , character string , list , Tuple and other contents .

For example, a Chinese English cross reference table can be represented by a dictionary .
my_dict = {"red": " gules ", "green": " green ", "blue": " blue "} print(my_dict) print(type(
The output result is :
{'red': ' gules ', 'green': ' green ', 'blue': ' blue '} <class 'dict'>
Now we need to establish a new understanding of the dictionary , A dictionary is a one-to-one correspondence between keys and values .

<>1.2 Gets the value of the dictionary

The key value is defined through the dictionary , Get the value through the key , Therefore, duplicate keys are not allowed in the dictionary . The syntax format of getting the value in the dictionary is :
my_dict = {"red": " gules ", "green": " green ", "blue": " blue "} print(my_dict["red"])
Look closely at the acquisition of very similar elements in the list , Just replace the index position with the key .

<>1.3 Add element to dictionary , Modify element , Delete element

Add element

Adding an element to the dictionary is very simple , You only need the following syntax to implement it .
my_dict[ key ] = value
For example, in the color translation dictionary just now, an orange corresponding key value is added , The code is as follows :
my_dict = {"red": " gules ", "green": " green ", "blue": " blue "} my_dict["orange"] = " orange "
If you want to add more key value correspondence in the dictionary , Write it down in sequence .

Modify element

Modify the element in the dictionary. Remember that the exact value should be called the value of the modified element , For example, the code red Corresponding value gules Change to Light red , Complete with the following code .
my_dict = {"red": " gules ", "green": " green ", "blue": " blue "} my_dict["red"] = " Light red "
adopt my_dict[ Key to modify ] = New value To complete the task .

Delete element

If you want to delete a specific element from the dictionary , Just pass del Keyword plus my_dict[ Key of the element to be deleted ] Can be completed .
my_dict = {"red": " gules ", "green": " green ", "blue": " blue "} del my_dict["red"] print(
The above content can delete specific elements , Using a dictionary clear method , You can empty the dictionary .
my_dict = {"red": " gules ", "green": " green ", "blue": " blue "} my_dict.clear() print(
The above content will be output {} This symbol represents an empty dictionary .

In addition to clearing the dictionary , You can also delete dictionary variables directly .
my_dict = {"red": " gules ", "green": " green ", "blue": " blue "} del my_dict print(my_dict)
After deleting dictionary variables , In print my_dict Program direct error reporting , Tips name ‘my_dict’ is not defined
Variable undefined , When deleting a dictionary, be careful not to delete the whole dictionary by mistake , Unless the program requires this .

<>1.4 Supplementary knowledge of dictionary

Empty dictionary

In fact, I mentioned just now how an empty dictionary is created , The syntax for creating an empty dictionary is as follows :
my_dict = {}
Empty dictionaries are generally used for logical placeholders , It's so complicated. What's logical occupancy , It's a trick to declare first and expand later .

Gets the number of dictionary elements

Both lists and tuples can be used len To get the number of elements , The same method applies to dictionaries , The syntax format is as follows :
my_dict_length = len(my_dict)
The number of elements in an empty dictionary is 0, You can try it .

Dictionary readability writing

In many cases, a program can not be completed by one person alone , Need a team to cooperate , How to make your code readable ( Others can understand ) Getting higher becomes very important when writing code . Dictionary in order to increase readability , It is recommended to define one element per line .
my_dict = {"red": " gules ", "green": " green ", "blue": " blue "} print(my_dict)
<>2 Dictionary traversal

The dictionary also needs to traverse every element in the output , For the dictionary, we already know that it is composed of key value pairs , Then the corresponding traversal output content has all key values , All keys , All values .

<>2.1 Key to traverse the dictionary - value

Calling dictionary items Method can get all the key values of the dictionary , For example, the following code :
my_dict = {"red": " gules ", "green": " green ", "blue": " blue "} print(my_dict.items())
The content is entered as :
dict_items([('red', ' gules '), ('green', ' green '), ('blue', ' blue ')])
Next, loop out the dictionary contents , There are several different ways of writing , Try to write the following code first , Learning knowledge points .
my_dict = {"red": " gules ", "green": " green ", "blue": " blue "} # Directly to my_dict Traverse for item
in my_dict: print(item) # ergodic my_dict of items method for item in my_dict.items():
print(item) # ergodic my_dict of items method , Combined use key And value receive for key,value in my_dict.
items(): print(" key :{}, value :{}".format(key,value))
Please refer to the above three output contents by yourself .

* The first output is all the keys ;
* The second method outputs each key value pair as a tuple ;
* The third way is to output keys and values directly through the assignment between variables and tuples .
For the assignment between variables and tuples, refer to the subordinate code :
a,b = (1,2) print(a) print(b)
Note that when assigning variables in this way, the variables on the left must correspond to the elements in the tuple on the right , A variable corresponds to an item in a tuple , The order also corresponds . If not, the following error will occur
ValueError: too many values to unpack .

<>2.2 Key to traverse the dictionary

What we learned above is to traverse the key values of the dictionary , You can go directly through keys Method to get all the keys of the dictionary , For example, the following code :
my_dict = {"red": " gules ", "green": " green ", "blue": " blue "} for key in my_dict.keys():
<>2.3 Traverse dictionary values

have keys Method get key , The corresponding is through values Get all values .
This place is too similar to the above , If you want to be a qualified programmer , At the beginning of learning, the amount of code per day cannot be reduced , So this part is for you .

<>3 Combination of dictionary and other data types

First realize that a dictionary is a container , It can contain any data type . A dictionary is also a data type , It can be contained by container classes such as lists and dictionaries themselves .
It's nice, isn't it , Its core is very simple , After reading the code, you will understand .

<>3.1 List nested dictionary

See the effect directly , A list can nest dictionaries .
my_list = [{"name": " eraser ", "age": 18}, {"name": " Big eraser ", "age": 20}] print(
my_list) print(my_list[0])
<>3.2 Dictionary nested list

The value of an element in the dictionary can be a list , The details are as follows :
my_dict = {"colors": [" gules "," green "], "nums": [1,2,3,4,5], "name": [" eraser "]} print(
<>3.3 Dictionary nested dictionary

The value of the dictionary can be any data type , That can naturally be the dictionary type , So you should be able to read the following code .
my_dict = {"colors": {"keys": [" gules ", " green "]}, "nums": [1, 2, 3, 4, 5], "name": [
" eraser "]} print(my_dict)
The above contents are very simple , To sum up, it's all dolls .

<>4 Dictionary method

The dictionary has some special methods that need to be explained separately , If you want to see all the methods in the dictionary , According to use dir Built in function call .

<>4.1 fromkeys method

The purpose of this method is to create a dictionary , The syntax format is as follows :
# Note that this method is passed directly dict call #seq It's a sequence , Can be tuple , It can also be a dictionary my_dict = dict.fromkeys(seq)
Next, actually create a dictionary through this method .
my_list = ['red', 'green'] my_dict = dict.fromkeys(my_list) # Output the following {'red':
None, 'green': None} print(my_dict) my_dict1 = dict.fromkeys(my_list, " Dictionary value ")
The first way is to find that all values in the output dictionary are None(Python Special values in , Equivalent to empty ), This content is because the dictionary default value is not set , Default to
None, If necessary, initialize the value when defining the dictionary , The second parameter in the method can be assigned .

<>4.2 get method

get Method is used to get a value from a key , If it does not exist, it can be set to return a default value , For example, the following code :
my_dict = {"red": " gules ", "green": " green ", "blue": " blue "} print(my_dict.get("red"))
# Return to red print(my_dict.get("red1")) # return None print(my_dict.get("red1",
" Set a default value that cannot be returned "))
<>4.3 setdefault method

setdefault Method and get The purpose of the method is basically the same , The difference is when setdefault When the specified key cannot be found , The key value will be inserted into the dictionary , For example, the following code :
my_dict = {"red": " gules ", "green": " green ", "blue": " blue "} print(my_dict.setdefault(
"red")) # Return to red print(my_dict.setdefault("orange")) # return None print(my_dict) #
output {'red': ' gules ', 'green': ' green ', 'blue': ' blue ', 'orange': None}
The result of the last line of code output already contains the key orange And value None, You can use dict.setdefault(“orange”,“ orange ”)
Test the default values .

<>4.4 pop method

This method is used to delete dictionary elements , The syntax format is as follows :
ret_value = dict.pop(key[,default])
Now that this standard format has been written , Let's supplement the specification of syntax format first , for example dict.pop(key[,default]) in key Indicates a required parameter ,[]
The included parameters are not required , In this way, you can understand what the above grammatical format is .
my_dict = {"red": " gules ", "green": " green ", "blue": " blue "} # Delete specified item ret_value = my_dict
.pop('red') # Output deleted red print(ret_value) # View dictionary {'green': ' green ', 'blue': ' blue '} print
(my_dict )
in use pop If you find a way key, The key value pair is deleted , If not found key Will return defalut Set value , If the value is not set , Will report an error .
my_dict = {"red": " gules ", "green": " green ", "blue": " blue "} # Delete specified item , If it is not set, the returned value cannot be found , Direct error reporting
ret_value= my_dict.pop('red2') # Delete specified item , can't find key1 Returns the value set later ret_value = my_dict.pop(
'red1'," The returned value was not found ")
<> summary

The dictionary is the same as the list , Tuples are the same Python
Very important data types in , The dictionary has more usage scenarios because of the concept of key value pairs , The advice of eraser at the beginning of learning is to type the code well , First establish a pair Python Cognitive whole , Snowballing
Python, This is only the first time .