koshish kharel koshish kharel - 26 days ago 6
Python Question

How do i convert list to dictionary in python?

i have 2 list in when i try to convert them to dict my output is random can anybody help?

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

Answer

As mentioned in the comments, you need to use an OrderedDict if you want to rely on the ordering of elements in your dictionary:

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

It can be accessed in the same way as a normal dict:

>>> x = OrderedDict(zip(a, b))
>>> x['abc']
''
Comments