Look it up in the dictionary and use the Python dictionary
After learning the list and tuple, they are arranged in order, so you can use the index to get the value. What this blog wants to learn is the dictionary. As can be seen from the above, the dictionary can't get the value according to the index, that is, there is no sequential and non sequential data structure.
Basic operation of dictionary
Definition of dictionary
A dictionary can be regarded as a list data structure and a container that can hold many other data types. However, the elements in the dictionary are represented by "key value", and the "key value" appears in pairs. The relationship between keys and values can be described as taking values through keys (this is the core concept of a dictionary, just like looking up a dictionary through radicals).
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 value of the dictionary, i.e. value 1 and value 2 in the above format, can be numeric value, string, list, tuple, etc.
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(my_dict))
The output result is:
{'red': 'gules', 'green': 'green', 'blue': 'blue'} <class 'dict'>
Now we need to establish the cognition of the dictionary again. The dictionary establishes the one-to-one correspondence from key to value.
Gets the value of the dictionary
Dictionaries are defined by key values, and values are obtained by keys. Therefore, duplicate keys are not allowed in dictionaries. The syntax format of getting the value in the dictionary is:
my_dict = {"red": "gules", "green": "green", "blue": "blue"} print(my_dict["red"])
When you look closely, it is very similar to the acquisition of elements in the list, just replacing the index position with the key.
Add, modify and delete elements in the dictionary
Add element
Adding an element to the dictionary is very simple and can be realized only through the following syntax format.
my_dict[key] = value
For example, in the color translation dictionary just now, an orange corresponding key value is added, and the code is as follows:
my_dict = {"red": "gules", "green": "green", "blue": "blue"} my_dict["orange"] = "orange" print(my_dict)
If you want to add more key value correspondence in the dictionary, you can write it in turn.
Modify element
Modify the element in the dictionary. Remember that the exact value should be called modifying the element value. For example, modify the red value corresponding to red in the code to light red, and complete it through the following code.
my_dict = {"red": "gules", "green": "green", "blue": "blue"} my_dict["red"] = "Light red" print(my_dict)
Pass my_dict [key to modify] = modify the new value to complete the task.
Delete element
If you want to delete a specific element in the dictionary, you only need to add my through the del keyword_ Dict [key of element to be deleted] can be completed.
my_dict = {"red": "gules", "green": "green", "blue": "blue"} del my_dict["red"] print(my_dict)
Specific elements can be deleted from the above contents. The dictionary can be emptied by using a clear method of the dictionary.
my_dict = {"red": "gules", "green": "green", "blue": "blue"} my_dict.clear() print(my_dict)
The above content will output {} the symbol represents an empty dictionary.
In addition to clearing the dictionary, you can also delete the dictionary variables directly.
my_dict = {"red": "gules", "green": "green", "blue": "blue"} del my_dict print(my_dict)
After deleting the dictionary variable, print my_ The dict program directly reports an error and prompts name 'my'_ The dict 'is not defined variable is undefined. When deleting the dictionary, be sure not to delete the whole dictionary by mistake, unless the program requires such implementation.
Supplementary knowledge of dictionary
Empty dictionary
In fact, I mentioned how to create an empty dictionary just now. The syntax for creating an empty dictionary is as follows:
my_dict = {}
Empty dictionaries are generally used for logical placeholders. They are so complex. What is called logical placeholders is a small skill to declare first and then expand later.
Gets the number of dictionary elements
Both lists and tuples can use len to obtain the number of elements. The same method is applicable to dictionaries. The syntax format is as follows:
my_dict_length = len(my_dict)
The number of elements in the empty dictionary is 0. You can try it.
Dictionary readability writing
In many cases, a program can not be completed independently by one person and needs the cooperation of a team. How to improve the readability of your code (which others can understand) 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)
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. The corresponding traversal output content has all key values, all keys and all values.
Key value traversal dictionary
Call the items method of the dictionary to obtain all the key values of the dictionary, such as the following code:
my_dict = {"red": "gules", "green": "green", "blue": "blue"} print(my_dict.items())
The content input is:
dict_items([('red', 'gules'), ('green', 'green'), ('blue', 'blue')])
Next, loop out the dictionary content. There are several different writing methods. First try to write the following code to learn the knowledge points.
my_dict = {"red": "gules", "green": "green", "blue": "blue"} # Directly to my_dict traversal for item in my_dict: print(item) # Ergodic my_ items method of Dict for item in my_dict.items(): print(item) # Ergodic my_ The items method of dict and receive it with key and value 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 keys;
- The second method outputs each key value pair as a tuple;
- The third method outputs 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 the tuple, and the order also corresponds. If not, the following error will appear: too many values to unpack.
Key to traverse the dictionary
What we learned above is to traverse the key values of the dictionary. You can directly obtain all the keys of the dictionary through the keys method, such as the following code:
my_dict = {"red": "gules", "green": "green", "blue": "blue"} for key in my_dict.keys(): print(key)
Traverse dictionary values
There is a keys method to obtain keys, corresponding to obtaining all values through values.
This place is too similar to the above content. If you want to be a qualified programmer, you can't reduce the amount of code every day at the beginning of learning, so this part is left to you.
Combination of dictionary and other data types
First realize that a dictionary is a container that can contain any data type. Dictionary is also a data type, which can be contained by container classes such as list and dictionary itself.
Really? The core is very simple. You will understand it after reading the code.
List nested dictionary
Look at 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])
Dictionary nested list
The values of elements in the dictionary can be lists, as follows:
my_dict = {"colors": ["gules","green"], "nums": [1,2,3,4,5], "name": ["eraser"]} print(my_dict)
Dictionary nested dictionary
The value of the dictionary can be any data type, which 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, they are dolls.
Dictionary method
There are some special methods in the dictionary that need to be explained separately. If you want to view all the methods in the dictionary, you can use the built-in function call of dir.
fromkeys method
The purpose of this method is to create a dictionary. The syntax format is as follows:
# Note that this method is called directly through dict # seq is a sequence, which can be a tuple or 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 {'red': None, 'green': None} print(my_dict) my_dict1 = dict.fromkeys(my_list, "Dictionary value") print(my_dict1)
In the first way, it is found that all values in the output dictionary are None (special values in Python, equivalent to null). This content is because the default value of the dictionary is not set, and the default value is None. If you need to initialize the value when defining the dictionary, you can assign a value to the second parameter in the method.
get method
The get method is used to obtain the value through the key. If it does not exist, it can be set to return a default value, such as 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 to None print(my_dict.get("red1","Set a default value that cannot be returned"))
setdefault method
The setdefault method is basically the same as the get method. The difference is that when setdefault cannot find the specified key, it will insert the key value 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 to None print(my_dict) # Output {'red': 'red', 'green': 'green', 'blue': 'blue', 'orange': None}
The output of the last line of code already contains the key orange and the value None. You can test the default value by using dict.setdefault("orange", "orange").
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, first supplement the specification of syntax format. For example, in dict.pop(key[,default]), key indicates mandatory parameters, and [] includes non mandatory parameters, so you can understand what the above syntax 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 )
When using the pop method, if the key is found, the key value pair will be deleted. If the key is not found, the value set by default will be returned. If the value is not set, an error will be reported.
my_dict = {"red": "gules", "green": "green", "blue": "blue"} # Delete the specified item. If there is no setting and the returned value cannot be found, an error will be reported directly ret_value = my_dict.pop('red2') # Delete the specified item and return the value set later if key1 is not found ret_value = my_dict.pop('red1',"The returned value was not found")
Summary of this blog
Dictionaries, like lists and tuples, are very important data types in Python. Dictionaries have more usage scenarios because of the concept of key value pairs. The idea given by the eraser at the beginning of learning is to play the code well. First establish an overall understanding of Python and snowball python. This is only the first time.
The last bowl of poisonous chicken soup
I naively thought that money is omnipotent. Later, I found that money is not omnipotent, it is omnipotent. O(∩ \ ∩) O ha ha~