我有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']}
答案 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']
''