"Learning Python with You Hand in Hand" 22-Dictionary

In the last article "Learning Python with You Hand in Hand" 21-Tuples , we learned the definition, operation methods, and the method and application of tuple "unpacking". Today, the data structure I will introduce to you is a dictionary.

If the lists and tuples we learned before are all one-dimensional data sequences, then the data structure of the dictionary including its presentation form is two-dimensional, because each element of the dictionary is a key-value pair composed of keys and values. Therefore, two dimensions are formed, which greatly expands the application scenarios of Python and our programming freedom.

1. Dictionary definition

A dictionary is a data collection of key-value pairs enclosed by a pair of large expansion signs {}. Each key (key) and value (value) are separated by ":", and each key-value pair is separated by ",". There is no limit to the number of key-value pairs in each dictionary. The syntax format of the dictionary is as follows:

dict = {key1:value1, key2:value2, key3:value3}

The keys in the dictionary must be unique, and the data types that can be used as keys must be immutable, such as strings, numbers, tuples, etc.

The values ​​in the dictionary can be repeated and can be any data type, such as strings, numbers, tuples, lists, dictionaries, and collections that we will introduce later.

In [1]: dict1 = {'A': 'Apple', 'B': 'Ball', 'C': 'Cat', 'D': 'Dog', 'E': 'Elephont'}   # 是不是很像“字典”?
        dict1
Out[1]: {'A': 'Apple', 'B': 'Ball', 'C': 'Cat', 'D': 'Dog', 'E': 'Elephont'}

In [2]: dict2 = {'A': 'Apple', 'B': 'Ball', 'C': 'Cat', 'D': 'Dog', 'E': 'Elephont', 'A': 'Aillgater'}   # 当键重复时不会报错,但是只有后一个值会被记住
        dict2
Out[2]: {'A': 'Aillgater', 'B': 'Ball', 'C': 'Cat', 'D': 'Dog', 'E': 'Elephont'}

In [3]: dict3 = {1: 'Apple', 'B': 1, ('C', 2): True, '3': ['Dog', 4, False], (1, '2', 'ASD): (Elephont,), (1, 2, (1, 2)): 'Apple'}   # 各种不同数据类型的键和值,且值可以重复
        dict3
Out[3]: {1: 'Apple',
         'B': 1,
         ('C', 2): True,
         '3': ['Dog', 4, False],
         (1, '2', 'ASD'): ('Elephont',),
         (1, 2, (1, 2)): 'Apple'}
         
In [4]: dict4 = {}   # 定义空字典
        dict4
Out[4]: {}

↓↓↓**********Extended content**********↓↓↓

Starting from this article, some extended content explanations will be added, and the above symbols will be used to distinguish this part of the content, so that some friends who have the ability to learn can expand or learn more. For other friends, you can choose to skip this part of the content temporarily, and it will not have any impact on the subsequent learning. You can rest assured.

What is added here is that in the last article "Learning Python with You Hand in Hand" 21-Tuples , we said that although tuples cannot be modified, the objects inside the tuple elements can be modified. Although it is also a tuple, this type of tuple cannot be used as a dictionary key.

In [5]: dict5 = {'B': 1, (1, 2, [1, 2]): 'Apple'}   # 从第三个实例的元组嵌套元组变成了元组嵌套列表
Out[5]: ---------------------------------------------------------------------------
        TypeError                                 Traceback (most recent call last)
        in
        ----> 1 dict5 = {'B': 1, (1, 2, [1, 2]): 'Apple'}   # 从第三个实例的元组嵌套元组变成了元组嵌套列表

        TypeError: unhashable type: 'list'

It can be seen from the above that it is an unhashable type of error, which means that the list cannot be hashed. The so-called cannot be hashed, which means that it cannot be used as a dictionary key.

Here is a simple function hash(), which can determine whether an object is immutable, or whether an object can be used as a dictionary key. If there is a return value, it means that the object is immutable and can be used as the key of the dictionary. If an error is reported, it means that the object is mutable and cannot be used as the key of the dictionary.

In [6]: hash((1, 2, [1, 2]))   # 报错,说明不能作为字典的键
Out[6]: ---------------------------------------------------------------------------
        TypeError                                 Traceback (most recent call last)
        in
        ----> 1 hash((1, 2, [1, 2]))   # 报错,说明不能作为字典的键

        TypeError: unhashable type: 'list'

After understanding these contents, we can understand such a data structure of the dictionary from a more professional perspective. Dictionary is the only mapping type in python language. The hash value (key, key) in the mapping type object and the pointed object (value, value) have a one-to-many relationship, so the dictionary can also be understood as a variable hash table.

In order for everyone to understand a special data type like a dictionary, and the principle that only immutable objects can be used as dictionary keys, the above paragraph is a little bit deeper. If you seem to be struggling, you can skip it for now. Friends who can understand, you can also try again to be hashed, or the object that can be used as the key of the dictionary, what is the return value after the hash() function (for example: hash('A')) .

↑↑↑**********Extended content**********↑↑↑

The dictionary is changeable like the list, and can be added, deleted, and modified. At the same time, the dictionary is relatively unordered, so it cannot be searched or partially intercepted by slicing and indexing. Below, we will talk about the various operations of dictionary addition, deletion, modification, and query.

2. Dictionary lookup

The dictionary lookup is very interesting. It is completely different from our previous method of slicing and indexing. It is the same as when we look up a dictionary. First find a key value (key), and then find the value (value) through this key value. Just like when we browse the web and enter the URL to access the web, so the search process of the dictionary is also a visit process.

The way to access the dictionary value is to put the key of the value (value) to be looked up in square brackets, just as we put the position value in the square brackets when indexing, the return value obtained is the corresponding key (key) The value (value).

In [7]: dict6 = {'A': 'Apple', 'B': 'Ball', 'C': 'Cat', 'D': 'Dog', 'E': 'Elephont'}  

In [8]: print("dict6['A']: {},dict6['C']: {}。".format(dict6['A'], dict6['C']))   # 访问的键如果存在于字典中,就返回键对应的值
Out[8]: dict6['A']: Apple,dict6['C']: Cat。

In [9]: dict6['F']   # 访问的键如果不存在于字典中,就报错
Out[9]: ---------------------------------------------------------------------------
        KeyError                                  Traceback (most recent call last)
        <ipython-input-16-6d56e56ab35b> in <module>
        ----> 1 dict6['F']   # 访问的键如果不存在于字典中,就报错

        KeyError: 'F'

3. Addition, deletion and modification of dictionary

The method of adding key-value pairs to the dictionary is very simple, that is, you can directly assign new keys to the dictionary. If the key already exists, the original value of the key will be overwritten and replaced with the new value, which is equivalent to modification.

In [10]: dict6['F'] = 'Fox'   # 新的键值对会被添加到字典中
         dict6
Out[10]: {'A': 'Apple',
          'B': 'Ball',
          'C': 'Cat',
          'D': 'Dog',
          'E': 'Elephont',
          'F': 'Fox'}
In [11]: dict6['A'] = 'Aillgater'   # 新的值会替换原来键'A'对应的值'Apple',即修改
         dict6
Out[11]: {'A': 'Aillgater',
          'B': 'Ball',
          'C': 'Cat',
          'D': 'Dog',
          'E': 'Elephont',
          'F': 'Fox'}

To delete a dictionary, you can either delete a key-value pair in the dictionary, or empty the dictionary (the dictionary still exists) to make it an "empty dictionary", or delete the dictionary directly (the dictionary does not exist).

In [12]: del dict6['A']   # 删除键值对
         dict6
Out[12]: {'B': 'Ball', 'C': 'Cat', 'D': 'Dog', 'E': 'Elephont', 'F': 'Fox'}

In [13]: dict6.clear()   # 清空字典,但字典仍然存在,是一个空字典
         dict6
Out[13]: {}

In [14]: del dict6   # 删除字典,字典不存在了
         dict6
Out[14]: ---------------------------------------------------------------------------
         NameError                                 Traceback (most recent call last)
         in
               1 del dict6   # 删除字典,字典不存在了
         ----> 2 dict6
         
         NameError: name 'dict6' is not defined

4. Dictionary function

There are not many functions involved in dictionaries, including len(), which calculates the number of dictionary key-value pairs, and str(), which converts a dictionary into a string. Among them, str() is a function we have learned before, and it can also convert numbers, lists, tuples, etc. into strings for output.

For ordinary dictionaries, these two functions are easy, and there is no need for examples. Here we see what the result will be when the dictionary includes duplicate keys.

In [15]: dict7 = {'A': 'Apple', 'B': 'Ball', 'C': 'Cat', 'D': 'Dog', 'E': 'Elephont', 'A': 'Aillgater'}

In [16]: len(dict7)
Out[16]: 5

In [17]: str(dict7)
Out[17]: "{'A': 'Aillgater', 'B': 'Ball', 'C': 'Cat', 'D': 'Dog', 'E': 'Elephont'}"

5. Dictionary method

There are many methods for dictionaries, and they are very important, like .keys() and .values(), which are indispensable methods when programming using dictionaries. At the same time, there are .pop(), .update(), etc., which are also often used. use. Below we will introduce in detail the various methods of the dictionary.

By convention, the various methods of the dictionary in the rookie tutorial are listed first. If necessary, you can directly click the link to view. Several important methods will be introduced and exemplified later.

Serial number

Function and description

1

radiansdict.clear()

Delete all elements in the dictionary

2

radiansdict.copy()

Returns a shallow copy of a dictionary

3

radiansdict.fromkeys()

Create a new dictionary, use the elements in the sequence seq as the keys of the dictionary, and val is the initial value corresponding to all the keys of the dictionary

4

radiansdict.get(key, default=None)

Return the value of the specified key, if the value is not in the dictionary, return the default value

5

key in dict

If the key is in the dictionary dict, return true, otherwise return false

6

radiansdict.items()

Return a traversable (key, value) tuple array as a list

7

radiansdict.keys()

Return an iterator, which can be converted to a list using list()

8

radiansdict.setdefault(key, default=None)

Similar to get(), but if the key does not exist in the dictionary, the key will be added and the value will be set to default

9

radiansdict.update(dict2)

Update the key/value pairs of dictionary dict2 to dict

10

radiansdict.values()

Return an iterator, which can be converted to a list using list()

11

pop(key[,default])

Delete the value corresponding to the given key of the dictionary, and the return value is the deleted value. The key value must be given. Otherwise, the default value is returned.

12

popitem ()

Randomly return and delete the last pair of keys and values ​​in the dictionary.

As mentioned earlier, .keys() and .values() are the two most important methods of the dictionary. Their function is to provide iterators of dictionary keys and values ​​respectively. In layman's terms, they will output all the keys and all of the dictionary respectively. value.

In [18]: dict8 = {'A': 'Apple', 'B': 'Ball', 'C': 'Cat', 'D': 'Dog', 'E': 'Elephont'}

In [19]: list(dict8.keys())
Out[19]: ['A', 'B', 'C', 'D', 'E']

In [20]: list(dict8.values())
Out[20]: ['Apple', 'Ball', 'Cat', 'Dog', 'Elephont']

In [21]: list(dict8)   # 当.keys()或.values()被省略时,其作用与写上.keys()相同
Out[21]: ['A', 'B', 'C', 'D', 'E']

In [22]: tuple(dict8)   # 转化成元组输出也是这样
Out[22]: ('A', 'B', 'C', 'D', 'E')

In [23]: str(dict8)   # 但转化成字符串输出就不一样了
Out[23]: "{'A': 'Apple', 'B': 'Ball', 'C': 'Cat', 'D': 'Dog', 'E': 'Elephont'}"

In the above example, we did not directly return the result of dict8.keys() or dict8.values(), but converted it into a list for output. This is because dict8.keys() returns an iterator of dictionary keys, not a data structure. Converting it into a list or tuple for output allows us to better manipulate the keys of the dictionary in the subsequent code, and we can also use the characteristics of lists and tuples for development.

But it’s not that the results of this iterator like dict8.keys() cannot be output, but this iterator will be used more for iteration such as for loops, rather than directly output or the next code data enter.

In [24]: dict8.keys()   # 返回值是一个迭代器
Out[24]: dict_keys(['A', 'B', 'C', 'D', 'E'])

In [25]: for letter in dict8.keys():
             print(letter)
Out[25]: A
         B
         C
         D
         E

The above is just a simple example of using the dictionary.keys() method as an iterator. In the next article, we will also have an in-depth discussion on the dictionary’s.keys() method and the.values() method to see how these methods can be used What interesting small programs have been developed.

Let me introduce some other more important methods through a few examples.

In [26]: seq = ('A', 'B', 'C', 'D', 'E')   # 当val省略时,字典中各个键对应的值都为空
         dict.fromkeys(seq)   # 从一个序列生成字典,序列值为字典的键
Out[26]: {'A': None, 'B': None, 'C': None, 'D': None, 'E': None}

In [27]: seq = ('A', 'B', 'C', 'D', 'E')   # 当val为某个值时,字典中各个键对应的值都为该值
         dict.fromkeys(seq, (1 ,2))
Out[27]: {'A': (1, 2), 'B': (1, 2), 'C': (1, 2), 'D': (1, 2), 'E': (1, 2)}

In [28]: dict9 = {'A': 'Apple', 'B': 'Ball', 'C': 'Cat', 'D': 'Dog', 'E': 'Elephont'}
         'F' in dict9   # 判断一个字典中是否存在某个键
Out[28]: False

In [29]: dict9.pop('A')   # 注意与上面讲的del的区别,pop方法会在删除键值对的同时返回被删除的键对应的值,而del只是删除键值对没有返回值
Out[29]: 'Apple'

In [30]: dict9
Out[30]: {'B': 'Ball', 'C': 'Cat', 'D': 'Dog', 'E': 'Elephont'}

In [31]: dict9.update({'A': 'Aillgater', 'F': 'Fox'})   # 合并两个字典,对于原字典中已经存在的键,当update()中的字典也存在相同的键,新的值会覆盖原来的值。
         dict9
Out[31]: {'B': 'Ball',
          'C': 'Cat',
          'D': 'Dog',
          'E': 'Elephont',
          'A': 'Aillgater',
          'F': 'Fox'}

The above is what this article introduces to the dictionary. Since dictionaries are very important, when introducing other applications of dictionaries, we need to use several functions that we have not learned. The length is a bit long and it is not convenient for everyone to read and learn. Therefore, the dictionary is divided into two articles for introduction. In the next article, I will first introduce a few very commonly used Python built-in sequence functions, and then use these functions to introduce you to other application scenarios of the dictionary, so stay tuned.

 

 


Thanks for reading this article! If you have any questions, please leave a message and discuss together ^_^

To read other articles in the "Learning Python with You Hand in Hand" series, please follow the official account and click on the menu selection, or click the link below to go directly.

"Learning Python with You Hand in Hand" 1-Why learn Python?

"Learning Python with you hand in hand" 2-Python installation

"Learning Python with You Hand in Hand" 3-PyCharm installation and configuration

"Learning Python with You Hand in Hand" 4-Hello World!

"Learning Python with You Hand in Hand" 5-Jupyter Notebook

"Learning Python with You Hand in Hand" 6-String Identification

《手把手陪您学Python》7——字符串的索引

《手把手陪您学Python》8——字符串的切片

《手把手陪您学Python》9——字符串的运算

《手把手陪您学Python》10——字符串的函数

《手把手陪您学Python》11——字符串的格式化输出

《手把手陪您学Python》12——数字

《手把手陪您学Python》13——运算

《手把手陪您学Python》14——交互式输入

《手把手陪您学Python》15——判断语句if

《手把手陪您学Python》16——循环语句while

《手把手陪您学Python》17——循环的终止

《手把手陪您学Python》18——循环语句for

《手把手陪您学Python》19——第一阶段小结

《手把手陪您学Python》20——列表

《手把手陪您学Python》21——元组

For Fans:关注“亦说Python”公众号,回复“手22”,即可免费下载本篇文章所用示例语句。

亦说Python——Python爱好者的学习分享园地
 

Guess you like

Origin blog.csdn.net/mnpy2019/article/details/102607566