我想把这些结合起来:

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

在单个词典中:

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

当前回答

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

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

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

其他回答

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

所有答案总结如下:

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}
import pprint

p = ['A', 'B', 'C']
q = [5, 2, 7]
r = ["M", "F", "M"]
s = ['Sovabazaar','Shyambazaar','Bagbazaar','Hatkhola']


def makeDictUsingAlternateLists1(**rest):
    print("*rest.keys() : ",*rest.keys())
    print("rest.keys() : ",rest.keys())
    print("*rest.values() : ",*rest.values())
    print("**rest.keys() : ",rest.keys())
    print("**rest.values() : ",rest.values())
    [print(a) for a in zip(*rest.values())]
    
    [ print(dict(zip(rest.keys(),a))) for a in zip(*rest.values())]
    print("...")
    
    
    finalRes= [ dict( zip( rest.keys(),a))  for a in zip(*rest.values())] 
    return finalRes
    
l = makeDictUsingAlternateLists1(p=p,q=q,r=r,s=s)
pprint.pprint(l)    
"""
*rest.keys() :  p q r s
rest.keys() :  dict_keys(['p', 'q', 'r', 's'])
*rest.values() :  ['A', 'B', 'C'] [5, 2, 7] ['M', 'F', 'M'] ['Sovabazaar', 'Shyambazaar', 'Bagbazaar', 'Hatkhola']
**rest.keys() :  dict_keys(['p', 'q', 'r', 's'])
**rest.values() :  dict_values([['A', 'B', 'C'], [5, 2, 7], ['M', 'F', 'M'], ['Sovabazaar', 'Shyambazaar', 'Bagbazaar', 'Hatkhola']])
('A', 5, 'M', 'Sovabazaar')
('B', 2, 'F', 'Shyambazaar')
('C', 7, 'M', 'Bagbazaar')
{'p': 'A', 'q': 5, 'r': 'M', 's': 'Sovabazaar'}
{'p': 'B', 'q': 2, 'r': 'F', 's': 'Shyambazaar'}
{'p': 'C', 'q': 7, 'r': 'M', 's': 'Bagbazaar'}
...
[{'p': 'A', 'q': 5, 'r': 'M', 's': 'Sovabazaar'},
 {'p': 'B', 'q': 2, 'r': 'F', 's': 'Shyambazaar'},
 {'p': 'C', 'q': 7, 'r': 'M', 's': 'Bagbazaar'}]
 
"""

这样地:

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

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