2013-01-31 100 views
1

字典後保持正確的順序時,大約有1,2或3個單元只如何保持字典爲了荏苒

>>> a = ["dorian", "strawberry", "apple"] 
>>> b = ["sweet", "delicious", "tasty"] 
>>> c = dict(zip(a, b)) 
>>> c 
{'dorian': 'sweet', 'strawberry': 'delicious', 'apple': 'tasty'} 

但是,當有超過3元,訂單被打破

>>> a = ["dorian", "strawberry", "apple", "coconut"] 
>>> b = ["sweet", "delicious", "tasty", "yum"] 
>>> c = dict(zip(a, b)) 
>>> c 
{'strawberry': 'delicious', 'coconut': 'yum', 'dorian': 'sweet', 'apple': 'tasty'} 

任何人都可以請解釋爲什麼發生這種情況?謝謝

+1

字典不保存順序 – Hoopdady

回答

6

Python字典不保留任何順序,您應該使用OrderedDict

In [7]: from collections import OrderedDict as od 

In [8]: a = ["dorian", "strawberry", "apple"] 

In [9]: b = ["sweet", "delicious", "tasty"] 

In [10]: dic=od(zip(a,b)) 

In [11]: dic 
Out[11]: OrderedDict([('dorian', 'sweet'), ('strawberry', 'delicious'), ('apple', 'tasty')]) 
1

字典是地圖數據結構。你永遠不能保證線性的順序。犧牲這個你可以在底層實現中獲得速度。

+0

我一半想到-1這一個,因爲它是非常有可能在地圖上做出訂單保證,而不犧牲所有那麼多的速度。 (也就是說,如果將值保存在雙向鏈表中,則可以在插入/刪除操作中保持不變的開銷,或者在樹中開銷log(n)並保持字典按鍵或值排序)。 – millimoose