2017-07-15 169 views
1

我想排序字典的字典。我的字典裏是這樣的,除了大約有幾百萬的條目與不同的用戶名,日期和數字:排序字典內的Python字典

{'RandomUserName': defaultdict(<type 'int'>, {'6/30/15': 2}), 
'AnotherRandomUserName': defaultdict(<type 'int'>, {'5/25/16': 8}), 
'AThirdRandomUserName': defaultdict(<type 'int'>, {'1/12/15': 5})} 

我要作爲排序依據的數字在項目結束本字典。我知道不可能對字典進行排序,並且只能返回排序的表示。這正是我想要做的。

我一直在尋找如何排序字典內的字典的答案,但所有的答案都假設我們知道鍵值前的關鍵。如果我們不呢?我如何根據最後的整數對它進行排序?

非常感謝,感謝任何答案!

+1

的可能的複製[排序按值Python字典(HTTPS ://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value) – alfasin

+0

你檢查了這個[鏈接](https://stackoverflow.com/questions/613183/sort-a-python-字典的值) – imanzabet

+0

如果'RandomUserName'包含帶2個鍵的'dict',如'{'6/30/15':2,'6/30/16':3}'? – randomir

回答

1

我想到的第一個解決方案是拼合該詞典,然後對結果列表進行排序。

例如:

dictionary_of_dictionaries = { 
    'RandomUserName': {'6/30/15': 2}, 
    'AnotherRandomUserName': {'5/25/16': 8}, 
    'AThirdRandomUserName': {'1/12/15': 5} 
} 


flattened = [(k,) + tuple(dic.iteritems()) for k, dic in dictionary_of_dictionaries.iteritems()] 
print flattened 

打印:

[('AnotherRandomUserName', ('5/25/16', 8)), ('RandomUserName', ('6/30/15', 2)), ('AThirdRandomUserName', ('1/12/15', 5))] 

然後對該列表進行排序

flattened.sort(key= lambda x:x[1][1]) 
print flattened 

,然後打印出你想要的順序條目。

[('RandomUserName', ('6/30/15', 2)), ('AThirdRandomUserName', ('1/12/15', 5)), ('AnotherRandomUserName', ('5/25/16', 8))] 

請沒有在這個第一個解決方案,我假定第二庫僅包含一個日期字段。有了一個更復雜的例子,你必須確保內部字典的元組總是以相同的順序變平。


,解決了這個問題溶液(會不會很高性能的,如果你的內心詞典包含噸田)

dictionary_of_dictionaries = { 
    'RandomUserName': {'6/30/15': 2 , 'name' : 'foo'}, 
    'AnotherRandomUserName': {'5/25/16': 8, 'name' : 'bar'}, 
    'AThirdRandomUserName': {'1/12/15': 5, 'name' : 'baz' } 
} 


flattened = [(k,) + tuple(sorted(dic.iteritems(), key=lambda x: x[0])) for k, dic in dictionary_of_dictionaries.iteritems()] 
print flattened 


flattened.sort(key= lambda x:x[1][1]) 
print flattened 
+0

這工作!我很感激Thunderzz –