Python: add the key to each list item, and then convert to dictionary
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}
精彩评论