Home > Backend Development > Python Tutorial > Tuple to dictionary

Tuple to dictionary

高洛峰
Release: 2016-10-20 10:12:33
Original
2538 people have browsed it

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])
Copy after login

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])]
Copy after login

The above code is more efficient than the following Equivalent code:

>>> d = {}
>>> for k, v in s:
...     d.setdefault(k, []).append(v)
...
>>> d.items()
Copy after login

[('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()
Copy after login

[('i', 4), ('p', 2), ('s', 4), ('m', 1) ]


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template