2016-11-08 29 views
-4

我有2個列表,當我嘗試將它們轉換爲字典我的輸出是隨機的任何人都可以幫忙嗎?如何將列表轉換爲Python中的字典?

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

您將需要一個'OrderedDict'做到這一點。 Python中不排序Plain Dicts。 –

+0

字典未訂購。如果你需要訂單(你呢,真的嗎?),使用'OrderedDict'。 – jonrsharpe

+0

Python字典(在Python 3.6之前)本質上是無序的。如果你想保存命令,可以使用'collections.OrderedDict'或者使用Python 3.6(但它仍然處於Beta版)。 – Duncan

回答

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'] 
'' 
相關問題