5.1 dictionary introduction
Dictionary is a common data structure in python. It stores two sets of data and mapping relationship, which is similar to the single mapping in mapping relationship in mathematics. There are two sets of data in the dictionary, one is called key, and the other is called value. The key and value form a pair, and the corresponding is represented by a colon, that is, key:value. Each key:value is an element in the dictionary, and the elements are separated by commas, for example:
my_dict = {key1:value1, key2:value2, key3:value3}
The elements in the dictionary are not in order. Each element in the list is in order.
5.2 dictionary creation
There are two common ways to create Dictionaries: direct assignment and dict.
Direct assignment creation:
>>> cvtutorials = {"host_name" : "cvtutorials", "domain_name_suffix" : "com"} >>> cvtutorials {'host_name': 'cvtutorials', 'domain_name_suffix': 'com'}
Create using dict:
>>> cvtutorials = dict(host_name="cvtutorials", domain_name_suffix="com") >>> cvtutorials {'host_name': 'cvtutorials', 'domain_name_suffix': 'com'}
5.3 ACCESS Dictionary
The dictionary name and index are required to access the dictionary (the index in the dictionary is key):
Dictionary name [key]
cvtutorials = dict(host_name="cvtutorials", domain_name_suffix="com") print(cvtutorials["host_name"]) print(cvtutorials["domain_name_suffix"])
The operation results are as follows:
>>> cvtutorials = dict(host_name="cvtutorials", domain_name_suffix="com") >>> print(cvtutorials["host_name"]) cvtutorials >>> print(cvtutorials["domain_name_suffix"]) com
dict.get(key, default=None): returns the value of the specified key. If the value is not in the dictionary, the default value is returned.
>>> cvtutorials = {'host_name': 'cvtutorials', 'domain_name_suffix': 'com'} >>> cvtutorials.get("host_name") 'cvtutorials'
The biggest difference between the dict.get(key) method and dict[key]: when the key does not exist, the former will not report an error, and the latter will report an error:
>>> cvtutorials = {'host_name': 'cvtutorials', 'domain_name_suffix': 'com'} >>> cvtutorials.get("host_name") 'cvtutorials' >>> cvtutorials.get("cv") >>> cvtutorials["cv"] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'cv'
dict.setdefault(key, default=None): if the key does not exist, the key will be added and the value will be set to default. For example:
>>> cvtutorials = {'host_name': 'cvtutorials', 'domain_name_suffix': 'com'} >>> cvtutorials.setdefault("host_name") 'cvtutorials' >>> cvtutorials {'host_name': 'cvtutorials', 'domain_name_suffix': 'com'} >>> cvtutorials.setdefault("domain") >>> cvtutorials {'host_name': 'cvtutorials', 'domain_name_suffix': 'com', 'domain': None}
5.4 dictionary traversal
dict.items: access all key value pairs of the dictionary and return iteratable objects (for the convenience of loop traversal in the following chapters). Take a simple example:
>>> cvtutorials = {"host_name" : "cvtutorials", "domain_name_suffix" : "com"} >>> cvtutorials.items() dict_items([('host_name', 'cvtutorials'), ('domain_name_suffix', 'com')])
dict.keys: access all keys in the dictionary and return iteratable objects. For example:
>>> cvtutorials = {"host_name" : "cvtutorials", "domain_name_suffix" : "com"} >>> cvtutorials.keys() dict_keys(['host_name', 'domain_name_suffix'])
dict.values: access all values in the dictionary and return iteratable objects. For example:
>>> cvtutorials = {"host_name" : "cvtutorials", "domain_name_suffix" : "com"} >>> cvtutorials.values() dict_values(['cvtutorials', 'com'])
5.5 modifying dictionaries and adding key value pairs
Here, we discuss modifying dictionaries and adding key value pairs together. It is similar to moving a file to a folder. If a file with the same name exists, it will be overwritten, and if it does not exist, it will be moved.
When adding a key value pair, if the key already exists, value will overwrite the original. If it does not exist, it is equivalent to adding a key value pair, as shown below:
>>> cvtutorials = {'host_name': 'cvtutorials', 'domain_name_suffix': 'com'} >>> cvtutorials["doc_build"] = "docsify" >>> cvtutorials {'host_name': 'cvtutorials', 'domain_name_suffix': 'com', 'doc_build': 'docsify'} >>> cvtutorials["doc_build"] = "docsify_github" >>> cvtutorials {'host_name': 'cvtutorials', 'domain_name_suffix': 'com', 'doc_build': 'docsify_github'}
Now, let's explain the original code: we first created a variable cvtutorials, and then added a key value pair. Because the original dictionary cvtutorials does not have a key named "doc\u build", this is an operation to add a key value pair. We printed the newly added key value pair. Finally, we assign a value to the key "docsify\u build" because the key "docsify\u build" already exists. At this time, the operation is to modify the dictionary. The modified results can be seen in 5 places.
dict1.update(dict2): add all key value pairs in one dictionary dict2 to another dictionary dict1.
>>> dict1 = {"1":"one", "2":"two"} >>> dict2 = {"3":"three", "4":"four"} >>> dict1.update(dict2) >>> dict1 {'1': 'one', '2': 'two', '3': 'three', '4': 'four'}
5.6 delete key value pairs
We use del to delete a key value pair. The standard form is:
del dictionary name [key]
For example, run the following code to see that the corresponding key value pair has been deleted.
>>> cvtutorials = {'host_name': 'cvtutorials', 'domain_name_suffix': 'com', 'doc_build': 'docsify_github'} >>> del cvtutorials["doc_build"] >>> cvtutorials {'host_name': 'cvtutorials', 'domain_name_suffix': 'com'}
dict.clear(): clear all elements in the dictionary.
>>> cvtutorials = {'host_name': 'cvtutorials', 'domain_name_suffix': 'com', 'domain': None} >>> cvtutorials.clear() >>> cvtutorials {}
5.7 other dictionary methods
len(): this method will calculate the length of the dictionary, that is, the number of keys in the dictionary. Please note that the dictionary variable here should be placed in the brackets of len(), which is different from the previous method.
>>> cvtutorials = {"host_name" : "cvtutorials", "domain_name_suffix" : "com"} >>> len(cvtutorials) 2
dict.copy(): copy the dictionary. For example:
>>> cvtutorials = {"host_name" : "cvtutorials", "domain_name_suffix" : "com"} >>> dict1 = cvtutorials.copy() >>> dict1 {'host_name': 'cvtutorials', 'domain_name_suffix': 'com'}