2012-04-09 173 views
3

像這樣的數據結構。python:排序字典上的字典

{ 
    'ford': {'count': 3}, 
    'mazda': {'count': 0}, 
    'toyota': {'count': 1} 
} 

什麼是排序的頂級字典的值內的count價值的最佳方式是什麼?

+0

字典是一種無序的數據類型,它不能被排序。你可以使用'collections.OrderedDict'。 – 0xc0de 2012-04-09 17:04:40

回答

11
d = {'ford': {'count': 3}, 
    'mazda': {'count': 0}, 
    'toyota': {'count': 1}} 

>>> sorted(d.items(), key=lambda (k, v): v['count']) 
[('mazda', {'count': 0}), ('toyota', {'count': 1}), ('ford', {'count': 3})] 

爲了使結果作爲一個字典,你可以使用collections.OrderedDict

>>> from collections import OrderedDict 
>>> ordered = OrderedDict(sorted(d.items(), key=lambda (k, v): v['count'])) 
>>> ordered 
OrderedDict([('mazda', {'count': 0}), ('toyota', {'count': 1}), ('ford', {'count': 3})]) 
>>> ordered.keys()   # this is guaranteed to come back in the sorted order 
['mazda', 'toyota', 'ford'] 
>>> ordered['mazda']  # still a dictionary 
{'count': 0} 

版本的擔憂:

  • 關於Python 2.x中,你可以使用d.iteritems(),而不是d.items()更好內存效率
  • collections.OrderedDict僅適用於Python 2.7和Python 3.2(a nd higher)
2

一個dicitonary是一個無序的數據結構,所以它不能被排序。你可以從你的字典d創建一個排序列表(或者,在Python 2.7,一個OrderedDict):

sorted(d.iteritems(), key=lambda item: item[1]["count"]) 

這個列表可以用作collections.OrderedDict構造函數的參數。

0

更清晰的方法是使用itemgetter,然後使用該值構建一個有序的字典,如其他建議。

>>> from operator import itemgetter 
>>> sorted(s,key=itemgetter,reverse=True) 
['ford', 'toyota', 'mazda'] 
0

如果要排序的值一些項目字典,結果你不能保存爲一個字典,因爲字典中不保留的元素加入的順序。 Fot,你必須使用OrderedDict。一種解決方案是,一旦排序,就會從(鍵值)元組列表中生成一個OrderedDict。

>>> collections.OrderedDict(sorted(d.iteritems(),key=lambda x:x[1]["count"],reverse=True)) 
OrderedDict([('ford', {'count': 3}), ('toyota', {'count': 1}), ('mazda', {'count': 0})]) 
>>> 
0

我覺得字典哈希表,因此不能真正排序。嘗試存儲排序的值成一個列表,其中可以進行排序:

l = [] 
for x in sorted(dictionary.keys()): 
    l.append([dictionary[x]]) 

如果你真的想保持的鑰匙,也許它們添加到列表中也是如此。只要確保在訪問列表時,甚至索引(0,2,4,...)是鍵和奇數索引是值(1,3,5,...)

0

如果您有的字典是名爲x,那麼你可以得到一個鍵列表: sorted_x = sorted(x,key = lambda a:x [a] ['count']) where sorted_x is: ['mazda','toyota', '福特']

然後可以打印: 對於i在sorted_x: 打印X [I]

結果: { '計數':0} { '計數':1} {」算「: 3}