Problem: Find out the small sentences in which some English words appear. Of course, it is implemented in Python. Of course, it is a dictionary. But how can we make a key correspond to a value of the list type, you cannot directly use the list append (), for example, DIC [Key]. append (value), because the interpreter does not know the DIC [Key] type. In a short time, it used a compromise solution, that is, to connect the value into a STR, and finally use Str. split () is converted to generate a list.
After reading the python cookbook, there is just a recipe on it to talk about how to deal with such a problem. Well, let's reveal the answer!
(1) repeated items are allowed in value.
CopyCodeThe Code is as follows: DIC = {}
Dic. setdefault (Key, []). append (value)
# Example:
D1.setdefault ('Bob _ hu', []). append (1)
D1.setdefault ('Bob _ hu', []). append (2)
Print D1 ['Bob _ hu'] # [1, 2]
(2) No repeated items in value.
Copy codeThe Code is as follows: DIC = {}
Dic. setdefault (Key, {}) [value] = 1
# Example:
D1.setdefault ('bob', {}) ['F'] = 1
D1.setdefault ('bob', {}) ['H'] = 1
D1.setdefault ('bob', {}) ['F'] = 1
Print D1 ['bob'] # {'H': 1, 'F': 1}