Python:将键添加到每个列表项,然后转换为字典

时间:2011-01-13 01:23:30

标签: python list dictionary

lst = [1,2,3,4]

我有硬编码密钥['one','two','three','four','five']

我希望字典像

{'one':1, 'two':2, 'three':3, 'four':4, 'five':None}

键总是超过列表中的项目数。

3 个答案:

答案 0 :(得分:9)

import itertools

lst = [1,2,3,4]
lst2 = ['one','two','three','four','five']

print dict(itertools.izip_longest(lst2, lst, fillvalue=None))
# {'five': None, 'four': 4, 'one': 1, 'three': 3, 'two': 2}

答案 1 :(得分:2)

以下是一些方法

>>> K=['one','two','three','four','five']
>>> V=[1,2,3,4]
>>> dict(map(None, K, V))
{'four': 4, 'three': 3, 'five': None, 'two': 2, 'one': 1}



>>> D=dict.fromkeys(K)
>>> D.update(zip(K,V))
>>> D
{'four': 4, 'three': 3, 'five': None, 'two': 2, 'one': 1}

答案 2 :(得分:1)

>>> dict(zip(keys, lst + [None]*(len(keys)-len(lst))))
{'four': 4, 'three': 3, 'five': None, 'two': 2, 'one': 1}