Home > Article > Backend Development > Tuple to dictionary
Tuples: 1. Wrapped in square brackets (()), they cannot be changed (although their contents can be). Tuples can be viewed as read-only lists
A. dict.fromkeys(S)
S is a list or tuple...
Use the elements in S as the key of the dictionary. The value defaults to None. You can also specify an initial value. The code example is as follows:
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 specifies the value type of the 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 is more efficient 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 given If default_dict is passed in int, 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) ]