更新时间:2023-02-17 12:58:59
使用 dict理解(Python 2.7 及更高版本):
Use a dict comprehension (Python 2.7 and later):
{key: value for (key, value) in iterable}
或者对于更简单的情况或早期版本的 Python,使用 dict
构造函数,例如:
Alternatively for simpler cases or earlier version of Python, use the dict
constructor, e.g.:
pairs = [('a', 1), ('b', 2)]
dict(pairs) #=> {'a': 1, 'b': 2}
dict([(k, v+1) for k, v in pairs]) #=> {'a': 2, 'b': 3}
给定单独的键和值数组,使用带有 dict 构造函数"noreferrer">zip
:
Given separate arrays of keys and values, use the dict
constructor with zip
:
keys = ['a', 'b']
values = [1, 2]
dict(zip(keys, values)) #=> {'a': 1, 'b': 2}
2) "zip'ped" from two separate iterables of keys/vals
dict(zip(list_of_keys, list_of_values))