我想把这些结合起来:
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'}
当前回答
所有答案总结如下:
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}
其他回答
用枚举法作为词典理解的解决方案:
dict = {item : values[index] for index, item in enumerate(keys)}
使用enumerate的循环的解决方案:
dict = {}
for index, item in enumerate(keys):
dict[item] = values[index]
keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
out = dict(zip(keys, values))
输出:
{'food': 'spam', 'age': 42, 'name': 'Monty'}
当我试图解决一个与图形相关的问题时,我产生了这种怀疑。我遇到的问题是,我需要定义一个空的邻接列表,并想用一个空列表初始化所有节点,这就是我想如何检查它是否足够快的时候,我的意思是,它是否值得执行zip操作,而不是简单的赋值键值对。在大多数情况下,时间因素是一个重要的破冰因素。所以我对两种方法都进行了timeit操作。
import timeit
def dictionary_creation(n_nodes):
dummy_dict = dict()
for node in range(n_nodes):
dummy_dict[node] = []
return dummy_dict
def dictionary_creation_1(n_nodes):
keys = list(range(n_nodes))
values = [[] for i in range(n_nodes)]
graph = dict(zip(keys, values))
return graph
def wrapper(func, *args, **kwargs):
def wrapped():
return func(*args, **kwargs)
return wrapped
iteration = wrapper(dictionary_creation, n_nodes)
shorthand = wrapper(dictionary_creation_1, n_nodes)
for trail in range(1, 8):
print(f'Itertion: {timeit.timeit(iteration, number=trails)}\nShorthand: {timeit.timeit(shorthand, number=trails)}')
对于n_nodes=10000000我明白了,
迭代次数:2.825081646999024速记:3.535717916001886
迭代:5.051560923002398速记:6.255070794999483
迭代次数:6.52859034499852速记:8.221581164998497
迭代次数:8.683652416999394速记:12.599181543999293
迭代次数:11.587241565001023速记员:15.27298851100204
迭代次数:14.816342867001367速记员:17.162912737003353
迭代次数:16.645022411001264速记员:19.976680120998935
您可以清楚地看到,在某一点之后,第n步的迭代方法超过了第n-1步的速记方法所花费的时间。
您可以使用以下代码:
dict(zip(['name', 'age', 'food'], ['Monty', 42, 'spam']))
但请确保列表的长度相同。如果长度不相同,请使用zip函数来切换较长的列表。
更自然的方法是使用词典理解
keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
dict = {keys[i]: values[i] for i in range(len(keys))}