我想把这些结合起来:

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

其他回答

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

如果在创建字典之前需要转换键或值,那么可以使用生成器表达式。例子:

>>> adict = dict((str(k), v) for k, v in zip(['a', 1, 'b'], [2, 'c', 3])) 

看一看《像蟒蛇一样的代码:惯用Python》。

所有答案总结如下:

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

没有zip函数的方法

l1 = [1,2,3,4,5]
l2 = ['a','b','c','d','e']
d1 = {}
for l1_ in l1:
    for l2_ in l2:
        d1[l1_] = l2_
        l2.remove(l2_)
        break  

print (d1)


{1: 'd', 2: 'b', 3: 'e', 4: 'a', 5: 'c'}