Question: Find some English words in which of the small sentences appear, of course, is implemented in Python, of course, with the dictionary, but how to make a key corresponding to a type of the list of value, directly with the list of append () is not possible, such as dic[key].append (value) , because the interpreter does not know the type of dic[key], when in a hurry, with a compromise scheme, is to use value into a str, and finally use Str.split () as a conversion, to generate a list.
Looking at the Python cookbook, there is just a recipe about how to deal with such a problem, well, find out the answer!
(1) A duplicate entry is allowed in value.
Copy Code code as follows:
DIC = {}
Dic.setdefault (key,[]). Append (value)
#如:
D1.setdefault (' Bob_hu ', []). Append (1)
D1.setdefault (' Bob_hu ', []). Append (2)
Print d1[' Bob_hu '] # [1,2]
(2) There are no duplicates in value.
Copy Code code as follows:
DIC = {}
Dic.setdefault (key,{}) [Value] = 1
#如:
D1.setdefault (' Bob ', {}) [' f '] = 1
D1.setdefault (' Bob ', {}) [' h '] = 1
D1.setdefault (' Bob ', {}) [' f '] = 1
Print d1[' Bob '] #{' h ': 1, ' F ': 1}