我想把这些结合起来:

keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']

在单个词典中:

{'name': 'Monty', 'age': 42, 'food': 'spam'}

当前回答

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

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]}

其他回答

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

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]}

所有答案总结如下:

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 = ['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')    
dict = {keys[i]: values[i] for i in range(len(keys))}

当我试图解决一个与图形相关的问题时,我产生了这种怀疑。我遇到的问题是,我需要定义一个空的邻接列表,并想用一个空列表初始化所有节点,这就是我想如何检查它是否足够快的时候,我的意思是,它是否值得执行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步的速记方法所花费的时间。