我想把这些结合起来:

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]

这里还有一个在字典中添加列表值的示例

list1 = ["Name", "Surname", "Age"]
list2 = [["Cyd", "JEDD", "JESS"], ["DEY", "AUDIJE", "PONGARON"], [21, 32, 47]]
dic = dict(zip(list1, list2))
print(dic)

始终确保“Key”(列表1)始终位于第一个参数中。

{'Name': ['Cyd', 'JEDD', 'JESS'], 'Surname': ['DEY', 'AUDIJE', 'PONGARON'], 'Age': [21, 32, 47]}

这样地:

keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print(dictionary) # {'a': 1, 'b': 2, 'c': 3}

Voila:-)成对dict构造函数和zip函数非常有用。

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步的速记方法所花费的时间。