2013-07-17 29 views
1

比方說,有一本字典Python的排序由Index

foo = {'b': 1, 'c':2, 'a':3 } 

我想遍歷這個字典在字典中的項目的出場順序。

for k,v in foo.items(): 
    print k, v 

打印

a 3 
c 2 
b 1 

,如果我們使用排序()函數:

for k,v in sorted(foo.items()): 
    print k, v 

打印

a 3 
b 1 
c 2 

但我需要他們在它們出現的順序字典我; e

b 1 
c 2 
a 3 

我該如何做到這一點?

+1

['OrderedDict'](HTTP ://docs.python.org/library/collections.html#collections.OrderedDict) –

回答

11

詞典沒有順序。如果你想這樣做,你需要在原始列表中找到一些排序方法。或者,按照保存順序將鍵保存在列表中,然後使用鍵作爲鍵訪問字典。

The Python Docs

最好是認爲字典作爲一個無序的鍵:值 對,該密鑰是唯一的(一個 字典之內)的要求。

示例 -

>>> testList = ['a', 'c', 'b'] 
>>> testDict = {'a' : 1, 'c' : 2, 'b' : 3} 
>>> for elem in testList: 
     print elem, testDict[elem] 


a 1 
c 2 
b 3 

或者更好的,使用OrderedDict -

>>> from collections import OrderedDict 
>>> testDict = OrderedDict([('a', 1), ('c', 2), ('b', 3)]) 
>>> for key, value in testDict.items(): 
     print key, value 


a 1 
c 2 
b 3 
+6

或者使用一個有序的字典 - 從2.7開始的標準庫的一部分,以及早期版本的通用配方。 http://docs.python.org/2/library/collections.html#collections.OrderedDict –

+0

是的。只是添加。謝謝。 :) –

+0

你的輸出是錯誤的OP的問題,a,c,b是錯誤的順序,應該是b,c,a – Stephan

2

ordered dictionary將不得不用來記住它們被存放在

順序
>>>from collections import OrderedDict 
>>>od = OrderedDict() 
>>>od['b'] = 1 
>>>od['c'] = 2 
>>>od['a'] = 3 
>>>print od 
OrderedDict([('b',1), ('c',2), ('a',3)] 
1

如果你只是想通過按鍵對它們進行排序做:

sorted_by_keys_dict = dict((y,x) for x,y in foo.iteritems()) 
for k,v in sorted(sorted_by_keys_dict.items()): 
    print v, k 

a 1 
c 2 
b 3 

或者乾脆:

for k,v in sorted(dict((y,x) for x,y in foo.iteritems()).items()): 
    print v, k 

a 1 
c 2 
b 3 
2

也許這?

sorted(foo, key=foo.get) 
1

看得更直接,你用來創建字典的順序不是字典的順序。該訂單是不確定的。

>>> {'b': 1, 'c':2, 'a':3 } 
{'a': 3, 'c': 2, 'b': 1} 
2

如果要多次使用OrderedDict,請使用OrderedDict,就像人們所說的那樣。:)如果你只是想要一個班輪爲一次性的,改變你的排序功能:

sorted(foo.items(), lambda a,b:a[1]-b[1]) 
+0

+1,但AFAIK,python文檔建議使用密鑰而不是比較器 –

+0

Yup,@roman,你的更好。 :) – roblinton

2

您可以通過一行代碼做到這一點:

>>> sorted(foo.items(), key=lambda x: x[1]) 
[('b', 1), ('c', 2), ('a', 3)] 
+0

雖然這在我上面給出的小例子中工作,但它並沒有在我的實際代碼中排序,這比這個 – oat

+0

大很多,這很奇怪,你能否從你的字典中提供一個樣本? –

+0

http://codepad.org/iOmou1Pz – oat