Since the dictionary is a variable sequence, we can manipulate key-value pairs in the dictionary. There are several common dictionary operations in Python:
Beginners should keep in mind that the dictionary is composed of key-value one by one. The key is the key to find the data. Python's operations on the dictionary are performed by key.
Adding new key-value pairs to the dictionary is very simple. You can directly assign a value to a key that does not exist. The specific syntax is as follows:
dictname [key] = value
Explanation of each part:
The following code illustrates the process of adding new elements to an existing dictionary:
age = {'Jason': 95} print (age) #Add new key-value pair age ['Nicole'] = 29 print (age) #Add new key-value pairs again age ['Harry'] = 10 print (age)
The output is:
{'Jason': 95}
{'Jason': 95, 'Nicole': 29}
{'Jason': 95, 'Nicole': 29, 'Harry': 10}
The name of the key in the Python dictionary cannot be modified, we can only modify the value.
The key of each element in the dictionary must be unique, so if the key of the newly added element is the same as the key of the existing element, the value corresponding to the key will be replaced by the new value, so as to achieve the purpose of modifying the value of the element . Look at the following code:
age = {'Jason': 95, 'Nicoe': 29, 'Harry': 10} print (age) age ['Harry'] = 80 print (age)
The output is:
{'Jason': 95, 'Nicoe': 29, 'Harry': 10}
{'Jason': 95, 'Nicoe': 29, 'Harry': 80}
It can be seen that instead of adding another {'Harry': 80} key-value pair to the dictionary, the value in the original key-value pair {'Harry': 10} has been modified.
If you want to delete the key-value pairs in the dictionary, you can still use the del statement. Example:
# Use the del statement to delete key-value pairs age = {'Jason': 95, 'Nicole': 29, 'Harry': 10} del age ['Nicole'] del age ['Harry'] print (age)
The output is:
{'Jason': 95}
If you want to determine whether a specified key-value pair exists in the dictionary, first determine whether there is a corresponding key in the dictionary. To determine whether a dictionary contains the keys of a specified key-value pair, you can use the in or not in operators.
It should be noted that, for dict, the in or not in operator is judged based on the key.
For example, the following code:
age = {'Jason': 95, 'Nicole': 29, 'Harry': 10} # Determine if a contains a key named 'Nicole' print ('Nicole' in age) # True # Determine if a contains a key named 'Peter' print ('Peter' in age) # False
The output is:
True
False
With the in (or not in) operator, we can easily determine whether a dictionary contains a key. If it exists, since the corresponding value can be easily obtained by the key, it is easy to determine the dictionary. Whether there are specified key-value pairs.
More Tutorials:
Python Installation - Linux (Ubuntu)More Python Exercises:
Python String Exercises