我想把这些结合起来:
keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
在单个词典中:
{'name': 'Monty', 'age': 42, 'food': 'spam'}
我想把这些结合起来:
keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
在单个词典中:
{'name': 'Monty', 'age': 42, 'food': 'spam'}
当前回答
对于那些需要简单代码但不熟悉zip的人:
List1 = ['This', 'is', 'a', 'list']
List2 = ['Put', 'this', 'into', 'dictionary']
这可以通过一行代码完成:
d = {List1[n]: List2[n] for n in range(len(List1))}
其他回答
keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
out = dict(zip(keys, values))
输出:
{'food': 'spam', 'age': 42, 'name': 'Monty'}
这样地:
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print(dictionary) # {'a': 1, 'b': 2, 'c': 3}
Voila:-)成对dict构造函数和zip函数非常有用。
对于那些需要简单代码但不熟悉zip的人:
List1 = ['This', 'is', 'a', 'list']
List2 = ['Put', 'this', 'into', 'dictionary']
这可以通过一行代码完成:
d = {List1[n]: List2[n] for n in range(len(List1))}
试试看:
>>> import itertools
>>> keys = ('name', 'age', 'food')
>>> values = ('Monty', 42, 'spam')
>>> adict = dict(itertools.izip(keys,values))
>>> adict
{'food': 'spam', 'age': 42, 'name': 'Monty'}
在Python2中,与zip相比,它的内存消耗也更经济。
用枚举法作为词典理解的解决方案:
dict = {item : values[index] for index, item in enumerate(keys)}
使用enumerate的循环的解决方案:
dict = {}
for index, item in enumerate(keys):
dict[item] = values[index]