Tuples: 1. Use brackets (()) to wrap, can not be changed (although their content can), tuples can be viewed as a read-only list
A. Dict.fromkeys (S)
S is a list or tuple ...
The key,value of the elements in S as the dictionary defaults to none, or you can specify an initial value, as shown in the following code example:
Mydict = Dict.fromkeys (' Hello ', True) for K in Mydict.keys (): print (k, mydict[k])
The output is as follows:
H True
E True
L True
o True
B. collections.defaultdict ([default_factory[,...]])
Default_factory the value type of the specified dictionary
>>> s = [(' Yellow ', 1), (' Blue ', 2), (' Yellow ', 3), (' Blue ', 4), (' Red ', 1)]>>> d = defaultdict (list) ;>> for K, V in S: ... D[k].append (v) ...>>> d.items (' blue ', [2, 4]), (' Red ', [1]), (' Yellow ', [1, 3])]
The above code efficiency is higher than the following equivalent code:
>>> d = {}>>> for K, V in S: ... D.setdefault (k, []). Append (v) ...>>> D.items ()
[(' Blue ', [2, 4]), (' Red ', [1]), (' Yellow ', [1, 3])]
If an int is passed to default_dict, it can be used to count:
>>> s = ' Mississippi ' >>> d = defaultdict (int) >>> for k in s: ... D[k] + = 1...>>> D.items ()
[(' I ', 4), (' P ', 2), (' s ', 4), (' m ', 1)]