2012-10-14 92 views
0

我需要基於鍵排序字典,然後返回與這些鍵相關的值。按鍵排序Python中的字典

ages = {40 : 'mother', 38 : 'father', 17 : 'me'} 
['me', 'father', 'mother'] # Should return this 

什麼是這樣做的最快的方式(表現爲對我來說真的一個問題,因爲排序得到在我的代碼調用數千次)。

非常感謝!

+2

這不是有效的Python語法,你有一個關鍵那是一個字符串。這是一個錯誤嗎? –

+1

如果在代碼中調用了數千次排序,則可能需要緩存一些結果或使用有序字典。 –

+1

請使用':'分隔key:值。 – kev

回答

4

因爲你的鑰匙是數字和超過字典默認迭代器返回鍵 - 你可以直接按鍵排序:

>>> ages = {40:'mother', 38:'father', 17:'me'} 
>>> [ages[k] for k in sorted(ages)] 
['me', 'father', 'mother'] 
+0

雖然技術上它不排序字典,它給OP所需的輸出。 –

+0

字典默認情況下不是「可排序的」。 –

+0

@MarkusUnterwaditzer:那麼OP要求輸出一個特定的輸出。由於這個答案提供了它,我認爲這是正確的。 – rubik

3

利用的sorted()zip()功能:

zip(*sorted(ages.items(), key=lambda item: item[0]))[1] 

第一它將詞典分類以創建元組列表(項目):

>>> sorted(ages.items()) 
[(17, 'me'), (38, 'father'), (40, 'mother')] 

然後只需要值:

>>> zip(*sorted(ages.items())[1] 
('me', 'father', 'mother') 

附:如果字典非常大,您可能需要考慮使用dict.iteritems(),它在Python 2上返回一個迭代器。在Python 3中,這是默認行爲,它由dict.items()提供。


替代的解決方案 - 使用operator.itemgetter()

>>> import operator 
>>> operator.itemgetter(*sorted(ages))(ages) 
('me', 'father', 'mother') 
+0

'key = lambda item:item [0]'是默認值,您可以放心地忽略它。 – georg

+0

@ thg435:好的,謝謝你指出! – rubik

2

無法排序字典由於這類藏品的性質。雖然Python的爲您提供了幾種選擇:要麼使用OrderedDict(保持插入鍵/值對的順序),或者只是按鍵,例如::排序

ages = {40 : 'mother', 38 : 'father', 17 : 'me'} 
ages_sorted = sorted(ages) 
# or ages.iterkeys()/.keys() (in Py3) which is a bit self-explanatory. 
+0

你不需要添加'.keys()',默認情況下字典是通過它們的鍵迭代的。 –

+0

是的。感謝您的糾正。 –

+0

另一方面,.keys()/ .iterkeys()是一個顯式調用,可以快速瞭解左側的變量類型。 –