Python dictionary-use dictionary + traverse dictionary + dictionary nesting

In python, a dictionary is a combination of key-value data items and exists in the form of {key:value}. Compared with lists, dictionaries are unordered, and members are accessed by key, while lists are accessed by position.
Dictionary description in python:
1. The dictionary can store any type of object;
2. Each key value key: value must be separated by a colon ":", and different key values ​​are separated by ","; the entire dictionary is included in {};
3. The key in each "key:value" key value must be unique and invariant (because the value of the key-value pair is obtained through the key)
This article will be divided into basic use dictionaries, traversal dictionaries and dictionaries Nested in three parts to describe.
1. Using the dictionary
This section talks about the creation-add-delete-change-check (access) of the dictionary (the dictionary name and key and value are clear for several operations) and the built-in functions related to the dictionary.
1. Create The
dictionary can be created directly through:
dictionary name = {key0:value0,key1:value1,key2:value2,...}
Sometimes to meet the needs of the project, the dictionary name = {} can be added and processed in subsequent use .

	#创建字典
    dict = {
    
    "name0":"张三","name1":"李四","name2":"王五"}

Note. If there is no such key in the called dictionary, the execution will report KeyError to indicate that there is no corresponding key in the dictionary , as shown below:
Insert picture description here
2. Increase The
dictionary is a dynamic structure, and you can add "key values" to it at any time. As follows:
Insert picture description here

3. To delete
the information that is no longer needed in the dictionary, you can use the del statement to delete the information corresponding to the corresponding "key value"
Insert picture description here4. To
modify the value in the dictionary, you must first specify the modified dictionary name and key, and correspond to the value, As shown below:
Insert picture description here5. Check the
value of the key-value pair is obtained by key
Insert picture description here
6. Dictionary-related built-in function
len (dict): calculate the number of elements in the dictionary, that is, the total number of keys
str (dict): string Form display dictionary
type (dict): returns the input variable type, where it should be a dictionary type. The specifics are as follows:
Insert picture description here
Second, traversing the dictionary
Since the number of key-value pairs contained in the dictionary is uncertain, it may be several or millions, so it often involves the traversal of the dictionary in normal times. We will describe the four aspects of traversing key, traversing value, traversing key-value pairs, and orderly traversing.
1. Traverse keys-the built-in method keys()
uses keys() in python to return all the keys in a dictionary in the form of a list.
keys() has no parameters, only the return value, and returns all the keys of a dictionary.
; Insert picture description here
When traversing keys, there is no difference between using dict.keys() and dict, as shown below:
Insert picture description here
2. Traversing values()
is similar to obtaining keys in python, traversing all values ​​of a dictionary using values() can be a list The form returns all the values ​​in a dictionary.
Insert picture description here
3. Traverse key: value-items()
Python dictionary (Dictionary) items() function returns a traversable (key, value) tuple array as a list.
Insert picture description here
Sometimes to facilitate data processing, two variables can be defined to receive key and value respectively, as shown below:
Insert picture description here
4. Traverse in order -sorted()
clearly records the correspondence between keys and values ​​in the dictionary, but the acquisition order is unpredictable , When you need to get in order, you can use sorted () to sort.
sorted() arranges the data in a sequence of copies of the key list.
1) Sort the keys and perform corresponding operations, as shown in the following example:
Insert picture description here
2) Sort by value, as shown below:
Insert picture description here
Due to the existence of duplicate values ​​in values, less traversal by values ​​is used. You can use a set to receive and remove duplicates.
The sorting of values ​​is added here to illustrate the sorted output, in essence, it is just the use of the sorted() method.
3. Dictionary nesting
In python programs, sometimes you need to store dictionaries in lists, sometimes you need to store lists in dictionaries, or even dictionaries in dictionaries. This is called nesting.
1. Store the dictionary in the list
When it comes to storing multiple objects , each object has some attributes. We can put the attributes and attribute values ​​of each object in a dictionary , and store many dictionaries in the list as the basic elements of the list. For example, everyone has a name, height, weight, and gender. We can store these attributes in a dictionary, and then store each dictionary in a list. When it needs to be modified, it can be modified according to the conditions. The procedure is as follows:

    person = []
    for i in range(0,5):
        person_demo = {
    
    "name":"张三","sex":"男","height":"175"}
        person.append(person_demo)
    print(person)
    for j in range(0,len(person)):
        if j == 0:
            person[j] ["name"] = "贝贝"
        elif j == 1:
            person[j] ["name"] = "京京"
        elif j == 2:
            person[j] ["name"] = "欢欢"
        elif j == 3:
            person[j] ["name"] = "迎迎"
        else:
            person[j] ["name"] = "妮妮"
    print(person)

The running results are as follows:
Insert picture description here
2. Store the list
in the dictionary. In the dictionary, when the key needs to be associated with multiple values, multiple values ​​can be stored in the list. For example, when introducing a person's hobbies, the hobbies are stored in the list.

person = {
    
    "name": "张三", "sex": "男", "height": "175", "爱好": ["阅读", "打乒乓球"]}

3. Store the dictionary in the dictionary.
As the list is stored in the dictionary above, when there are multiple people who need to store it, we can use the dictionary to store the dictionary. The dictionary selects the key attribute as the key value (select name):
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44801116/article/details/109697738