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}