Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:向每个列表项添加键,然后转换为字典_Python_List_Dictionary - Fatal编程技术网

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

Python:向每个列表项添加键,然后转换为字典,python,list,dictionary,Python,List,Dictionary,我有硬编码的钥匙['1','2','3','4','5'] 我想要这本字典 lst = [1,2,3,4] 键总是多于列表中的项数。这里有几种方法可以做到这一点 {'one':1, 'two':2, 'three':3, 'four':4, 'five':None} import itertools lst = [1,2,3,4] lst2 = ['one','two','three','four','five'] print dict(itertools.izip_longest(ls

我有硬编码的钥匙
['1','2','3','4','5']

我想要这本字典

lst = [1,2,3,4]

键总是多于列表中的项数。

这里有几种方法可以做到这一点

{'one':1, 'two':2, 'three':3, 'four':4, 'five':None}
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}

对于第一个示例,您只需执行:
dict(map(None,K,V))
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}
>>> 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}