4 回答
TA贡献2012条经验 获得超12个赞
试试这个:
>>> import itertools
>>> keys = ('name', 'age', 'food')
>>> values = ('Monty', 42, 'spam')
>>> adict = dict(itertools.izip(keys,values))
>>> adict
{'food': 'spam', 'age': 42, 'name': 'Monty'}
在Python 2中,与zip.
TA贡献1824条经验 获得超5个赞
想象一下你有: keys = ('name', 'age', 'food')values = ('Monty', 42, 'spam')制作以下词典的最简单方法是什么?
dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}
最具表现力的-Python2.7和3,DECT理解:
new_dict = {k: v for k, v in zip(keys, values)}
zip
izip
from itertools import izip as zip
new_dict = {k: v for k, v in zip(keys, values)}
Python 2,适合<=2.6
izip
itertools
zip
izip
from itertools import izip new_dict = dict(izip(keys, values))
Python 3
zip
itertools
new_dict = dict(zip(keys, values))
所有案件的结果:
>>> new_dict{'age': 42, 'name': 'Monty', 'food': 'spam'}
说明:
dict
>>> help(dict)class dict(object) | dict() -> new empty dictionary | dict(mapping) -> new dictionary initialized from a mapping object's | (key, value) pairs | dict(iterable) -> new dictionary initialized as if via: | d = {} | for k, v in iterable: | d[k] = v | dict(**kwargs) -> new dictionary initialized with the name=value pairs | in the keyword argument list. For example: dict(one=1, two=2)
>>> zip(keys, values)[('name', 'Monty'), ('age', 42), ('food', 'spam')]
>>> list(zip(keys, values))[('name', 'Monty'), ('age', 42), ('food', 'spam')]
zip
>>> zip(keys, values)<zip object at 0x7f0e2ad029c8>
zip
绩效较差的替代办法:
generator_expression = ((k, v) for k, v in zip(keys, values))dict(generator_expression)
dict((k, v) for k, v in zip(keys, values))
dict([(k, v) for k, v in zip(keys, values)])
业绩审查:
>>> min(timeit.repeat(lambda: {k: v for k, v in zip(keys, values)}))
0.7836067057214677
>>> min(timeit.repeat(lambda: dict(zip(keys, values))))
1.0321204089559615
>>> min(timeit.repeat(lambda: {keys[i]: values[i] for i in range(len(keys))}))
1.0714934510178864
>>> min(timeit.repeat(lambda: dict([(k, v) for k, v in zip(keys, values)])))
1.6110592018812895
>>> min(timeit.repeat(lambda: dict((k, v) for k, v in zip(keys, values))))
1.7361853648908436
TA贡献1777条经验 获得超10个赞
>>> keys = ('name', 'age', 'food')
>>> values = ('Monty', 42, 'spam')
>>> dict(zip(keys, values))
{'food': 'spam', 'age': 42, 'name': 'Monty'}
添加回答
举报