常用的Python中将列表转换为字典的方法
1.将元组列表转换为字典l1=[(1,'a'),(2,'b'),(3,'c'),(4,'d')]d1=dict(l1)print (d1)#Output:{1: 'a', 2: 'b', 3: 'c', 4: 'd'}2.将两个相同长度的列表转换成字典from itertools import zip_longestl1=[1,2,3,4,5,6,7]l2=['a','b','c','d']d1=
·
1.将元组列表转换为字典
l1=[(1,'a'),(2,'b'),
(3,'c'),(4,'d')]
d1=dict(l1)
print (d1)
#Output:{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
2.将两个相同长度的列表转换成字典
from itertools import zip_longest
l1=[1,2,3,4,5,6,7]
l2=['a','b','c','d']
d1=zip_longest(l1,l2)
print (d1)#Output:<itertools.zip_longest object at 0x00993C08>
#Converting zip object to dict using dict() contructor.
print (dict(d1))
#Output:{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: None, 6: None, 7: None}
3.将两个不同长度的列表转换成字典
l1=[1,2,3,4]
l2=['a','b','c','d']
d1=zip(l1,l2)
print (d1)#Output:<zip object at 0x01149528>
#Converting zip object to dict using dict() contructor.
print (dict(d1))
#Output:{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
更多推荐
已为社区贡献1条内容
所有评论(0)