2008-09-13 34 views

回答

49

標準python dict無法做到這一點。

有一個建議(PEP 372)向標準庫中的collections模塊添加一個「有序字典」(記錄插入順序)。它包括鏈接variousimplementationsofordereddictionaries(也可參見Python食譜中的這些tworecipes)。

如果您希望自己的代碼與「官方」版本兼容(如果提案最終被接受),您可能希望堅持使用PEP中的參考實現。

編輯:PEP被接受並在python 2.7和3.1中添加。見the docs

6

你不能使用基類字典類來做到這一點 - 它是由哈希排序。你可以建立你自己的字典,這個字典實際上是一個關鍵字,值對或者其他的列表,它們將被排序。

+2

您的字典實現可以改爲使用標準字典和列表 - 字典存儲鍵 - >值關聯,並且列表按照順序存儲密鑰y被插入。 – 2008-09-13 21:56:24

18

其他答案是正確的;這是不可能的,但你可以自己寫這個。但是,如果你不確定如何實際實現這樣的東西,這裏有一個完整的工作實現,它的子類是我剛剛編寫和測試的字典。 (請注意,值傳遞給構造的順序是不確定的,但會晚一點傳遞的值之前,你可以永遠只是不允許有序類型的字典要與值初始化)。

class ordered_dict(dict): 
    def __init__(self, *args, **kwargs): 
     dict.__init__(self, *args, **kwargs) 
     self._order = self.keys() 

    def __setitem__(self, key, value): 
     dict.__setitem__(self, key, value) 
     if key in self._order: 
      self._order.remove(key) 
     self._order.append(key) 

    def __delitem__(self, key): 
     dict.__delitem__(self, key) 
     self._order.remove(key) 

    def order(self): 
     return self._order[:] 

    def ordered_items(self): 
     return [(key,self[key]) for key in self._order] 


od = ordered_dict() 
od["hello"] = "world" 
od["goodbye"] = "cruel world" 
print od.order()   # prints ['hello', 'goodbye'] 

del od["hello"] 
od["monty"] = "python" 
print od.order()   # prints ['goodbye', 'monty'] 

od["hello"] = "kitty" 
print od.order()   # prints ['goodbye', 'monty', 'hello'] 

print od.ordered_items() 
# prints [('goodbye','cruel world'), ('monty','python'), ('hello','kitty')] 
+0

order_dict(('key_a','value_a'),('key_b','value_b'))是否正確排序?看起來_order會被設置爲__init__中的self.keys(),它是按散列順序排序的,而不是它輸入的順序?只是好奇。 – 2008-12-09 20:57:55

+0

你是對的,這就是爲什麼我說,「傳遞給構造函數的值的順序是未定義的,但會在稍後傳遞值之前出現」。可以對這些對象進行適當排序,但我不確定這是否是一種理想的行爲,因爲可以說這些對象是同時插入的。 – 2008-12-10 22:13:49

0

如果你不需要字典功能,並且只需要按照插入它們的順序返回元組,不會有更好的隊列工作嗎?

7

或者,只要有time.now()作爲元組的第一場關鍵的元組。

然後你可以用dictname.keys(),sort和voila檢索密鑰!

格里

+1

這使得無法準確瞭解何時插入字典中的條目是不可能的。它不比鍵值對更好。 – user2357112 2014-06-04 03:03:22

1

它,除非你存儲在單獨的列表中的鍵供以後參考是不可能的。

2

或使用任何用於PEP-372的實施方式的從pythonutils描述here,像odict module

我成功地使用了pocoo。組織實施,這是因爲你的

my_dict={} 
my_dict["foo"]="bar" 

my_dict=odict.odict() 
my_dict["foo"]="bar" 

更換一樣方便,需要的只是this file

1

你可以做的是插入一個鍵代表順序輸入的值,並然後在物品上撥打sorted()

>>> obj = {} 
>>> obj[1] = 'Bob' 
>>> obj[2] = 'Sally' 
>>> obj[3] = 'Joe' 
>>> for k, v in sorted(obj.items()): 
...  print v 
... 
Bob 
Sally 
Joe 
>>> 
6

使用OrderedDict(),因爲2.7版

的好奇心早晚的事情可供選擇:中

from collections import OrderedDict 
a = {} 
b = OrderedDict() 
c = OredredDict() 

a['key1'] = 'value1' 
a['key2'] = 'value2' 

b['key1'] = 'value1' 
b['key2'] = 'value2' 

c['key2'] = 'value2' 
c['key1'] = 'value1' 

print a == b #True 
print a == C#True 
print b == C#False 
相關問題