This structure is mapped in many languages, and the dictionary is the only built-in mapping type in Python.
Let's look at a dictionary example:
Phonebook = {' Alice ': ' 2341 ', ' Beth ': ' 9102 ', ' Cecil ': ' 3258 '}
The name is the key, the number is the value, the two are separated by a colon, the key in the dictionary is unique, and the value is not unique. An empty dictionary consists of two curly braces: {}. Here are a few more common dictionary operations:
- Len (d) Returns the number of key-value pairs in D
- D[K] Returns the value corresponding to the key K
- D[k] = V associates the value V to the key K
- Del D[k] Delete item with key K
- K in D check if D contains keys for key k
The contents of the dictionary can also be added as follows:
Here's a fun example:
Let's look at a cool example of a dictionary and string formatting combined:
This makes it clear and easy for us to modify the HTML text.
Let's explore some dictionary methods below:
1. Clear: Clears all entries in the dictionary, no return value
The usefulness of this method can be reflected by the following example:
As can be seen from the above example, when executing y=x, Y is bound to X, so as x changes, y also changes, but when x={},y is not emptied, Y is also associated with the original dictionary. When you want to empty both x and Y, you can use clear only.
2. Copy: Shallow copy, return a new dictionary with the same key-value pairs, for arrays and object type values, copy can only be shallow copy, that is, copy reference
Y changes to the machine array are reflected in x because they are using the same set of numbers.
A dictionary of the Python Way (iii)