开发者

Python: add the key to each list item, and then convert to dictionary

开发者 https://www.devze.com 2023-02-03 18:46 出处:网络
lst = [1,2,3,4] I have hard coded keys [\'one\',\'two\',\'three\',\'four\',\'five\'] and I want the dictionary like
lst = [1,2,3,4]

I have hard coded keys ['one','two','three','four','five']

and I want the dictionary like

{'one':1, 'two':2, '开发者_C百科three':3, 'four':4, 'five':None}

Keys are always more than the number of items in list.


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}


Here are a couple of ways to do it

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


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

精彩评论

暂无评论...
验证码 换一张
取 消