我想把这些结合起来:
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'}
当前回答
可以通过以下方式完成。
keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
dict = {}
for i in range(len(keys)):
dict[keys[i]] = values[i]
print(dict)
{'name': 'Monty', 'age': 42, 'food': 'spam'}
其他回答
用枚举法作为词典理解的解决方案:
dict = {item : values[index] for index, item in enumerate(keys)}
使用enumerate的循环的解决方案:
dict = {}
for index, item in enumerate(keys):
dict[item] = values[index]
2018-04-18
最佳解决方案仍然是:
In [92]: keys = ('name', 'age', 'food')
...: values = ('Monty', 42, 'spam')
...:
In [93]: dt = dict(zip(keys, values))
In [94]: dt
Out[94]: {'age': 42, 'food': 'spam', 'name': 'Monty'}
转换它:
lst = [('name', 'Monty'), ('age', 42), ('food', 'spam')]
keys, values = zip(*lst)
In [101]: keys
Out[101]: ('name', 'age', 'food')
In [102]: values
Out[102]: ('Monty', 42, '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相比,它的内存消耗也更经济。
所有答案总结如下:
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}
使用Python3.x,可以进行dict理解
keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
dic = {k:v for k,v in zip(keys, values)}
print(dic)
关于dict的理解,这里有一个例子:
>>> print {i : chr(65+i) for i in range(4)}
{0 : 'A', 1 : 'B', 2 : 'C', 3 : 'D'}