我想把这些结合起来:
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'}
当前回答
您可以使用以下代码:
dict(zip(['name', 'age', 'food'], ['Monty', 42, 'spam']))
但请确保列表的长度相同。如果长度不相同,请使用zip函数来切换较长的列表。
其他回答
keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
out = dict(zip(keys, values))
输出:
{'food': 'spam', 'age': 42, 'name': 'Monty'}
对于那些需要简单代码但不熟悉zip的人:
List1 = ['This', 'is', 'a', 'list']
List2 = ['Put', 'this', 'into', 'dictionary']
这可以通过一行代码完成:
d = {List1[n]: List2[n] for n in range(len(List1))}
所有答案总结如下:
l = [1, 5, 8, 9]
ll = [3, 7, 10, 11]
zip:
dict(zip(l,ll)) # {1: 3, 5: 7, 8: 10, 9: 11}
#if you want to play with key or value @recommended
{k:v*10 for k, v in zip(l, ll)} #{1: 30, 5: 70, 8: 100, 9: 110}
计数器:
d = {}
c=0
for k in l:
d[k] = ll[c] #setting up keys from the second list values
c += 1
print(d)
{1: 3, 5: 7, 8: 10, 9: 11}
枚举:
d = {}
for i,k in enumerate(l):
d[k] = ll[i]
print(d)
{1: 3, 5: 7, 8: 10, 9: 11}
keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
dic = {}
c = 0
for i in keys:
dic[i] = values[c]
c += 1
print(dic)
{'name': 'Monty', 'age': 42, 'food': 'spam'}
试试看:
>>> 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相比,它的内存消耗也更经济。