-4

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']}
koshish kharel
  • 347
  • 1
  • 4
  • 12
  • 2
    You will need an `OrderedDict` to do that. Plain dicts are not ordered in Python. – Frédéric Hamidi Nov 08 '16 at 16:30
  • Dictionaries are not ordered. If you need order (do you, really?), use an `OrderedDict`. – jonrsharpe Nov 08 '16 at 16:30
  • Python dictionaries (prior to Python 3.6) are inherently unordered. If you want to preserve order use a `collections.OrderedDict` or use Python 3.6 (but it is still in Beta). – Duncan Nov 08 '16 at 16:31
  • Dictionaries in Python 3.6 might still be unordered, only **kwargs is guaranteed to be ordered. – Francisco Nov 08 '16 at 16:34

1 Answers1

0

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']
''
brianpck
  • 8,084
  • 1
  • 22
  • 33