Hello, I'm brother Manon Feige. Thank you for reading this article. Welcome to one click three times.
This article mainly introduces the dictionary (dict) in Python data types. Let's talk about the dictionary thoroughly at once.
It's full of dry goods. It's recommended to collect it. You need to use it often. If you have any questions and needs, you are welcome to add V: wei158556 or send me a private letter ~.
What is a dictionary?
In the last article, we introduced [Python from introduction to mastery] (VI) Python's built-in data types - list and tuple, nine shallow and one deep, ten chapters, I don't believe you can't use them
Lists and tuple s are two very common sequences. Today we will introduce another widely used sequence Dictionary (dict). Even if you haven't come into contact with the data type dict, you must have heard of the term dictionary - > no one has ever used the famous Xinhua dictionary!!!
Seeing this picture, does it remind me of going to school as a child. Ha ha ha ha
Recall how we query a Chinese character through Xinhua dictionary? Is it according to pinyin to find Chinese characters? I believe everyone knows the specific search details. The process of querying the dictionary is mapped to the same principle. The dictionary (dict) in Python is to find the value through the key. The underlying data structure of the dictionary (dict) is the hash table structure.
How to use a dictionary?
After finishing the basic concept of the dictionary, let's talk about how to use the dictionary. Only what can be used is a good thing. This chapter will introduce the addition, deletion, modification and search of the dictionary. The basic structure of the dictionary is:
{'key1':'value1', 'key2':'value2', ..., 'keyn':valuen}
Where key1~keyn represents the key and value1~valuen represents the value corresponding to the key. It should be noted that all keys in the dictionary are unique (everyone is unique). There is and only one key can be null value None, and only immutable types can be used, such as string, integer, decimal and tuple. The value can be any data type supported by Python, and the value can be the null value None. There is no limit to the number of null values None.
Create a dictionary
There are many ways to create a dictionary. Here are some common methods.
The first method uses the {} symbol to create a dictionary. Its syntax structure is dictname = {key1 ':'value1','key2 ':'value2',...,'keyn ': valuen}
The second is to use the fromkeys method. Its syntax structure is dictname = dict.fromkeys(list, value=None). The list parameter represents the list of all keys in the dictionary, and the value parameter represents the default value. If it is not written, all values are null and None.
The third is to use the dict method, which can be divided into four cases:
- Dict() - > create an empty dictionary
- Dict (mapping) - > create a dictionary. During initialization, its key values are from the key and value in mapping.
- Dict (iterable) - > create a dictionary. During initialization, it will traverse iterable to get its key value.
for k, v in iterable: d[k] = v
- Dict (* * kwargs) - > * * kwargs is a variable function, and its calling syntax format is dict(key1=value1,key2=value2,...keyn=valuen), for example: dict(name = 'code farmer flying brother', age=17, weight=63)
The three methods of creating dictionaries have been introduced. Let's take a look at the examples below:
#1. Create a dictionary d = {'name': 'Mainong Feige', 'age': 18, 'height': 185} print(d) list = ['name', 'age', 'height'] # 2. fromkeys method dict_demo = dict.fromkeys(list) dict_demo1 = dict.fromkeys(list, 'test') print(dict_demo) print(dict_demo1) # Create a dictionary through dict() mapping and pass in a list or tuple demo = [('name', 'Mainong Feige'), ('age', 19)] dict_demo2 = dict(demo) print(dict_demo2) dict_demo21 = dict(name='Mainong Feige', age=17, weight=63) print(dict_demo21)
The operation result is:
{'name': 'Mainong Feige', 'age': 18, 'height': 185} {'name': None, 'age': None, 'height': None} {'name': 'test', 'age': 'test', 'height': 'test'} {'name': 'Mainong Feige', 'age': 19} {'name': 'Mainong Feige', 'age': 17, 'weight': 63}
Dictionary access
After the creation of the dictionary, let's take a look at the access of the dictionary. Dictionaries are different from lists and tuples. The elements in the dictionary are not stored in the memory area in turn; Therefore, the elements in the dictionary cannot be accessed through the index, but can only find the corresponding value through the key, There are two different ways to write it.
- The syntax format of the first method is dictname[key], where dictname represents the name of the dictionary and key represents the specified key. If the specified key does not exist, a KeyError error will be reported.
- The syntax format of the second method is dictname Get (key), where dictname represents the name of the dictionary and key represents the specified key. If the specified key does not exist, it returns None.
Take chestnuts as an example. The following code means to find the corresponding value according to the key name name.
dict_demo5 = {'name': 'Mainong Feige', 'age': 18, 'height': 185} print(dict_demo5['name']) print(dict_demo5.get('name')) print('Returns the result if the key does not exist=',dict_demo5.get('test'))
The operation result is:
Mainong Feige Mainong Feige Returns a result if the key does not exist= None
Add and modify key value pairs
The method of adding key value pairs is very simple. Its syntax structure is dictname[key]=value. If the key does not exist in the dictionary, a key value pair will be added. If the key exists in the dictionary, the value corresponding to the original key will be updated. Still for example: the result of the code in this example is to increase the key value pair sex = 'male', and change the value corresponding to the key height to 190.
# Add key value pair dict_demo6 = {'name': 'Mainong Feige', 'age': 18, 'height': 185} dict_demo6['sex'] = 'male' print('Results of adding key value pairs={0}'.format(dict_demo6)) # Modify key value pair dict_demo6['height'] = 190 print('Modify the result of key value pair={0}'.format(dict_demo6))
The operation result is:
Results of adding key value pairs={'age': 18, 'name': 'Mainong Feige', 'height': 185, 'sex': 'male'} Modify the result of key value pair={'age': 18, 'name': 'Mainong Feige', 'height': 190, 'sex': 'male'}
Of course, modifying and deleting key value pairs can also be implemented through the update method. The specific syntax format is: dictname Update (dict), where dictname is the name of the dictionary and dict is the value of the dictionary to be modified. This method can add or modify key value pairs. This method has no return value, that is, it modifies the element on the original dictionary. In the following example, the value of the key name is changed to Feifei 1024, and the value corresponding to the key age is changed to 25. And added the key value pair like = learning.
# update method dict_demo7 = {'name': 'Mainong Feige', 'age': 18, 'height': 185, 'width': 100} dict_demo7.update({'name': 'Feifei 1024', 'age': 25, 'like': 'study'}) print('update Method returns the result={}', dict_demo7)
The operation result is:
update Method returns the result={} {'height': 185, 'like': 'study', 'width': 100, 'name': 'Feifei 1024', 'age': 25}
Delete key value pair
There are three ways to delete key value pairs:
- The first is del dictname[key], which uses the Del keyword, where dictname is the name of the dictionary and key is the key to be deleted. If the key does not exist, a KeyError error will be reported.
- The second way is through the pop method, whose syntax structure is: dictname pop(key). This method is used to delete the specified key value pair. There is no return value. If the key does not exist, no error will be reported.
- The third way is through the popitem method, whose syntax structure is dictname popitem(). This method is used to delete the last key value pair in the dictionary. For example:
dict_demo10 = {'name': 'Mainong Feige', 'age': 18, 'height': 185, 'width': 100} # Delete key value pair del dict_demo6['height'] print('Delete key height Yes, the results after=', dict_demo6) # pop() method and popitem() method dict_demo10.pop('width') print('pop Method call delete key width Subsequent results=', dict_demo10) dict_demo10 = {'name': 'Mainong Feige', 'age': 18, 'height': 185, 'width': 100} dict_demo10.popitem() print('popitem Result after method call=', dict_demo10)
The operation result is:
Delete key height Yes, the results after= {'name': 'Mainong Feige', 'sex': 'male', 'age': 18} pop Method call delete key width Subsequent results= {'name': 'Mainong Feige', 'height': 185, 'age': 18} popitem Result after method call= {'width': 100, 'name': 'Mainong Feige', 'height': 185}
It can be seen that the key deleted by the popitem method is not the last key width, but the key age. And after deletion, the order of elements in the dictionary has changed.
Description of other methods:
- Judge whether the specified key exists in the dictionary. Its syntax structure is: key in dictname, where key is the key to find, and dictname is the dictionary name. In indicates whether the lookup key exists in the dictionary. If the lookup key no longer exists in the dictionary, the not in keyword is required. for instance:
dict_demo6 = {'name': 'Mainong Feige', 'age': 18, 'height': 185} print('Judgment key name Whether the result is=', ('name' in dict_demo6))
- Output all the keys in the dictionary. The called method is keys (), and its syntax structure is dictname keys(). Where dictname is the dictionary name.
- Output all the values in the dictionary. The called method is values (), and its syntax structure is dictname values().
- Output all key value pairs in the dictionary. The called method is items (), and its syntax structure is dictname items().
For example:
dict_demo7 = {'name': 'Mainong Feige', 'age': 18, 'height': 185, 'width': 100} print('keys Method returns the result=', dict_demo7.keys()) print('value Method returns the result=', dict_demo7.values()) print('item Method returns the result=', dict_demo7.items())
The output is:
keys Method returns the result= dict_keys(['width', 'name', 'height', 'age']) value Method returns the result= dict_values([100, 'Mainong Feige', 185, 18]) item Method returns the result= dict_items([('width', 100), ('name', 'Mainong Feige'), ('height', 185), ('age', 18)])
Format string using dictionary
In the sequence article, we introduced that the specifier can be converted in sequence. Its syntax format is: {num}, Num is the number, which is incremented from 0, and the string is formatted with the format method. However, this method also has disadvantages, that is, it is inconvenient to use when there are a large number of conversion specifiers in the string.
str = 'Mainong Feige{0},You will={1}' print(str.format('come on.', 'Promising'))
The output result is that come on, you must be promising. The parameters here should be transmitted in strict order.
At this time, we can format the string through the dictionary. Its syntax format is% (name)s, where% is a fixed writing method. Name corresponds to the key in the dictionary. S represents the type of value whose dictionary key is name. If it is a string, it is s. Finally, output the formatted string through str%dictname, where str is the original string and dictname is the name of the dictionary. Take a chestnut!
str = 'Man Nong Feige's No=%(num)s piece=%(article)s,hope=%(reader)s like' dict_demo12 = {'num': 250, 'article': 'article', 'reader': 'Readers'} print(str % dict_demo12)
The running result is code Nong Feige's article = 250, I hope = readers like it
summary
This article introduces the basic concepts and detailed usage of Python dictionary in detail, hoping to be helpful to readers.
Haowen recommendation
[Python from introduction to mastery] (VI) Python's built-in data types - list and tuple, nine shallow and one deep, ten chapters, I don't believe you can't use them
[Python from introduction to mastery] (V) Python's built-in data types - sequences and strings. They have no girlfriend, not a nanny, and can only be used as dry goods
[Python from introduction to mastery] (IV) what are the built-in data types of Python? Figure out
Python knowledge map
In order to better help more children learn about Python from the beginning to the end, I got a set of "Python stack knowledge atlas" from CSDN officials, with a size of 870mm x 560mm. After expansion, it can be the size of a desk or folded into the size of a book. Interested children can learn about it - scan the QR code in the figure below to buy it.
I have already bought it myself. It's very easy to use. Put the manual on the table and keep knowledge in mind
I'm brother Manon Feige. Thank you again for reading this article.