python合并两个列表成字典

问题

有两个列表如下:

1
2
keys = [1, 2, 3]
values = ['A', 'B', 'C']

最终结果,生成如下字典:

1
d = {1: 'A', 2: 'B', 3: 'C'}

解决办法

用zip函数生成一个列表(每个元素都是输入列表对应元素组成的元组),然后再用dict构造字典。

1
2
3
4
5
6
# Good
keys = [1, 2, 3]
values = ['A', 'B', 'C']
d = dict(zip(keys, values))

上面的办法要优于下面的办法:

1
2
3
4
5
6
7
8
# bad
keys = [1, 2, 3]
values = ['A', 'B', 'C']
d = {}
for i, key in enumerate(keys):
d[key] = values[i]

讨论

zip函数的原型如下:

1
2
3
4
5
6
7
8
9
def zip(seq1, seq2, *more_seqs):
"""
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences. The returned list is truncated
in length to the length of the shortest argument sequence.
"""
pass

dict构造字典有以下几种方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
class dict(object):
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
"""
pass

大师兄 wechat
欢迎关注我的微信公众号:Python大师兄