如何在python中将列表转换为字典?

时间:2016-11-08 16:28:42

标签: python list dictionary

我有2个列表,当我尝试将它们转换为dict时我的输出是随机的可以有人帮忙吗?

a=['abc', 'def', 'ghi', 'jkl', 'mno']
b=['', '', ['123', '456', '786', '989'], '', ['222', '888', '111', '333']]

print(dict(zip(a,b)))

output: {'def': '', 'ghi': ['123', '456', '786', '989'], 'jkl': '', 'abc': '', 'mno': ['222', '888', '111', '333']}

what i want is
{'abc':'', 'def':'', 'ghi':['123', '456', '786', '989'],'jkl':'','mno':['222', '888', '111', '333']}

1 个答案:

答案 0 :(得分:0)

如评论中所述,如果您想依赖字典中元素的排序,则需要使用OrderedDict

>>> from collections import OrderedDict
>>> OrderedDict(zip(a, b))
OrderedDict([('abc', ''), ('def', ''), ('ghi', ['123', '456', '786', '989']), ('jkl', ''), ('mno', ['222', '888', '111', '333'])])

可以使用与普通dict

相同的方式访问它
>>> x = OrderedDict(zip(a, b))
>>> x['abc']
''