與列表不同的字典沒有排序(並且沒有「排序」屬性)。因此,您無法依賴首次添加時按相同順序獲取項目。在Python中,如何輕鬆地從字典中檢索已排序的項目?
什麼是循環包含字符串作爲鍵值的字典並按鍵升序檢索它們的最簡單方法是什麼?
例如,你有這樣的:
d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
我想通過鍵排序按以下順序打印相關的值:
this is a
this is b
this is c
與列表不同的字典沒有排序(並且沒有「排序」屬性)。因此,您無法依賴首次添加時按相同順序獲取項目。在Python中,如何輕鬆地從字典中檢索已排序的項目?
什麼是循環包含字符串作爲鍵值的字典並按鍵升序檢索它們的最簡單方法是什麼?
例如,你有這樣的:
d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
我想通過鍵排序按以下順序打印相關的值:
this is a
this is b
this is c
這個片段將這樣做。如果你打算經常這樣做,你可能需要製作一個「分類鍵」方法或其他方法,以便讓眼睛更輕鬆。
keys = list(d.keys())
keys.sort()
for key in keys:
print d[key]
編輯:dF的解決方案更好 - 我忘了所有關於排序()。
你的意思是說你需要按鍵值排序的值嗎? 在這種情況下,這應該這樣做:
for key in sorted(d):
print d[key]
編輯:改爲使用排序(d),而不是排序(運行起來也()),感謝Eli的!
實際上,您可以直接在「排序鍵(d):」中說「無需說」d.keys()「,因爲迭代字典只是迭代其鍵。 – 2008-09-10 20:28:27
或更短,
for key, value in sorted(d.items()):
print value
不只是排序 - 避免查找 – 2008-09-10 20:13:08
>>> d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
>>> for k,v in sorted(d.items()):
... print v, k
...
this is a a
this is b b
this is c c
d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
ks = d.keys()
ks.sort()
for k in ks:
print "this is " + k
for key in sorted(d):
print d[key]
您也可以按值字典和控制排序順序:
import operator
d = {'b' : 'this is 3', 'a': 'this is 2' , 'c' : 'this is 1'}
for key, value in sorted(d.iteritems(), key=operator.itemgetter(1), reverse=True):
print key, " ", value
輸出:
B本是3
a這是2
c這是1
你的意思是「排序」而不是「排序」?看起來你的問題旨在排序字典,而不是訂購它。如果您的意思是「有序」,您可以使用集合模塊中的OrderedDict。這些字典記得在輸入了鍵/值對的順序:
from collections import OrderedDict
參考信息:https://docs.python.org/2/library/collections.html#collections.OrderedDict
是的,但排序不提供老的Python(預2.4),所以這個成語仍是有用。 – jmanning2k 2008-09-10 21:03:37