The path to Python (3): The Path to python
This structure is mapped in many languages, and the dictionary is the only built-in ing type in Python.
Here is an example of a dictionary:
phonebook = {'Alice':'2341', 'Beth':'9102', 'Cecil':'3258'}
The name is a key and the number is a value. The numbers are separated by colons. the dictionary's key is unique and the value is not unique. The empty dictionary consists of two braces :{}. Next we will introduce several common dictionary operations:
- Len (d) returns the number of key-value pairs in d.
- D [k] value corresponding to return key k
- D [k] = v associate the value v with the key k
- Del d [k] delete key k
- K in d check whether d contains key k items
You can also add dictionary content as follows:
Here is a fun example:
Next, let's look at a cool example of combining dictionary and string formatting:
In this way, the modification of html text becomes clear and easy.
Next, let's look at some dictionary methods:
1. clear: clear all items in the dictionary and no return value
The usage of this method can be reflected in the following example:
As shown in the preceding example, when y = x is executed, y is bound to x. As x changes, y also changes, but when x = {}, y is not cleared, and y is associated with the original dictionary. To clear both x and y, you can only use clear.
2. copy: Light copy. A new dictionary with the same key-value pairs is returned. For values of the array and object types, copy can only be light copy, that is, copy reference.
Y's modification to the machine array is reflected in x, because they use the same array.
Dictionary problems in python 30
Dict_keys is similar to a list but not a list. It is a view of the dictionary's key value ). Therefore, it neither uses the pop method nor the next method.
Python dictionary Problems
LetterCounts [letter] = \
LetterCounts. get (letter, 0) \ # obtain the key value of letter from the dictionary letterCounter. The default value is 0 (when no data is obtained ).
+ 1 # Add one
# Save the result to the letterCounts dictionary with the letter as the key