Basic knowledge of Python -- dictionary


       This article is about the basics of Python (from entry to practice) -- dictionaries. The basics of Python in this section mainly include: dictionaries, using dictionaries (creating, accessing, modifying, deleting), traversing dictionaries, and nesting.


Table of contents

1.1 Dictionary

1.2 Accessing the values ​​in the dictionary

 1.3 Add key-value pairs

 1.4 Modify the value in the dictionary

 1.5 Delete key-value pairs

 1.6 Dictionaries of similar objects

 1.7 Using get() to access values

Second, traverse the dictionary

2.1 Traverse all key-value pairs

 2.2 Traverse all keys in the dictionary

2.3 Traversing all keys in a dictionary in a specific order

 2.4 Traverse all values ​​in the dictionary

 3. Nesting

3.1 Storing dictionaries in lists

 3.2 Storing lists in dictionaries

 3.3 Storing dictionaries within dictionaries


1. Dictionary

1.1 Dictionary

       In python, a dictionary is a sequence of key-value pairs. Each value is associated with a value, and the associated value can be accessed using the key. The value associated with the key can be a number, string, list or even a dictionary, and any python object can be used as the value in the dictionary.

      In python, dictionaries are represented by a series of key-values ​​enclosed in curly braces ({}). Examples are as follows:

dog_0 = {'color' : 'black' , 'age' : 4}

        A key-value pair is two associated values. When a key is specified, Python will return the value associated with it. Keys and values ​​are separated by colons, and key values ​​are separated by commas. In a dictionary, you can store as many key-value pairs as you want. The simplest dictionary has only one key-value pair.

1.2 Accessing the values ​​in the dictionary

        To get the value associated with a key, specify the dictionary name followed by the key enclosed in square brackets. Examples are as follows:

dogs_0 = {'color': 'black' , 'age' : 4}
print(dogs_0['color'])

The output is as follows: will return the value associated with the key "color" in the dictionary dogs_0.

 1.3 Add key-value pairs

       A dictionary is a dynamic structure where key-value pairs can be added at any time. To add a key-value pair, specify the dictionary name, the key enclosed in square brackets, and the associated value accordingly. Examples are as follows:

dog_0 = {'color': 'black' , 'age' : 4}
print(dog_0)
dog_0['name'] = 'lili'
dog_0['weight'] = 16
print(dog_0)

The output is as follows:

 1.4 Modify the value in the dictionary

       To modify a value in a dictionary, specify the dictionary name, the key enclosed in square brackets, and the new value associated with that key. Examples are as follows:

dog_0 = {'color': 'black' , 'age' : 4}
print(dog_0)
dog_0['color'] = 'white'
print(dog_0)

The output is as follows:

 1.5 Delete key-value pairs

       The corresponding key-value pair can be completely deleted by using the del statement, and the dictionary name and the key to be deleted must be specified. Examples are as follows:

dog_0 = {'color': 'black' , 'age' : 4}
print(dog_0)
del dog_0['age']
print(dog_0)

The output is as follows:

 1.6 Dictionaries of similar objects

        In the previous example, the dictionary stores multiple information of an object, but the dictionary can also store the same information of many objects. Examples are as follows:

dog_color = {
    'lili': 'black' ,
    'haha' : 'white',
    'uu' : 'zizi' ,
    }
color = dog_color['haha']
print(f'Haha is {color}.')

The output is as follows:

 1.7 Using get() to access values

       When retrieving a value of interest from a dictionary with a key enclosed in square brackets, an error may be raised: an error will occur if the specified key does not exist. As far as dictionaries are concerned, the method get() can be used to return a default value when the specified key does not exist to avoid errors.

       The first parameter of the method get() is used to specify the key, which is essential; the second parameter is the value to be returned when the specified key does not exist, and is optional. Examples are as follows:

dog_0 = {'color': 'black' , 'age' : 4}
weight = dog_0.get('weight','No weight value assigned.')
print(weight)

The output is as follows:

      If the specified key may not exist, the method get() should be considered instead of using the square bracket notation.

Second, traverse the dictionary

2.1 Traverse all key-value pairs

       The for loop can be used to traverse the dictionary, and two variables can be declared to store the key and value in the key-value pair. The two variables can be any name. The second part of the for statement contains the dictionary name and the method items(), which returns a list of key-value pairs. Examples are as follows:

dog_0 = {'color': 'black' ,
         'age' : 4,
         'weight' : 16,
         }
for k,v in dog_0.items():
    print(f'\nK:{k}')
    print(f'v:{v}')

The output is as follows:

 2.2 Traverse all keys in the dictionary

       To traverse all the keys in the dictionary, use the method keys() . Examples are as follows:

dog_0 = {'color': 'black' ,
         'age' : 4,
         'weight' : 16,
         }
for information in dog_0.keys():
    print(information)

The output is as follows:

2.3 Traversing all keys in a dictionary in a specific order

       One way to return elements in a specific order is to sort the returned values ​​in a for loop. The following example uses the function sort() to obtain a copy of the list of keys in a specific order. Examples are as follows:

dog_0 = {'color': 'black' ,
         'age' : 4,
         'weight' : 16,
         }
for information in sorted(dog_0.keys()):
    print(information.title())

The output is as follows:

 2.4 Traverse all values ​​in the dictionary

       The method values() can be used to return a list of values, without any keys. Examples are as follows:

dog_0 = {'color': 'black' ,
         'age' : 4,
         'weight' : 16,
         }
for information in dog_0.values():
    print(information)

The output is as follows:

 3. Nesting

        Nesting : Store a sequence of dictionaries in a list, or store a list as a value in a dictionary.

3.1 Storing dictionaries in lists

      Dictionaries can be stored in lists. Examples are as follows:

dogs_0 = {'color':'green','age':4}
dogs_1 = {'color':'black','age':3}
dogs_2 = {'color':'white','age':2}

dogs = [dogs_0,dogs_1,dogs_2]
for dog in dogs:
    print(dog)

The output is as follows:

 3.2 Storing lists in dictionaries

    Whenever you need to associate a key to multiple values ​​in a dictionary, you can nest a list inside a dictionary. Examples are as follows:

pets = {
    'dogs':['jinmao','xueqiao'],
    'ducks':['yazi'],
    'cats':['yingduan','meiduan'],
    }

for name,pet in pets.items():
    print(f'\n{name.title()} are:')
    for pet in pets:
        print(f"\t{pet.title()}")

The output is as follows:

 3.3 Storing dictionaries within dictionaries

     You can nest dictionaries within dictionaries, but when you do, your code gets complicated.

     Here's an example (with dog names as keys, then store each dog information in a dictionary, and have those dictionaries as values ​​associated with usernames):

dogs = {
    'jinmao':{
        'color': 'black',
        'age' : 5,
        },
    'bandian':{
        'color': 'white',
        'age' : 9
        }
    }

for dog_information,dog in dogs.items():
    print(f'\nDog_information:{dog_information}')
    color = {dog['color']}
    age = {dog['age']}

    print(f'\tColor:{color}')
    print(f'\tAge:{age}')

The output is as follows:


Today's learning summary is here! If you have any questions, you can leave a message in the comment area~

If it helps everyone, you can click three times + pay attention to support~

Reference study books: Python programming from entry to practice (Second Edition)


 Series Article Directory

Python basic knowledge points--variables and simple data types

Python basic knowledge points--listPython

basic knowledge points--traverse lists, slices, tuples

Basic knowledge of Python -- if statement

Basic knowledge of Python -- dictionary 

Guess you like

Origin blog.csdn.net/m0_57787115/article/details/129344888