我想到的第一個解決方案是拼合該詞典,然後對結果列表進行排序。
例如:
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
的可能的複製[排序按值Python字典(HTTPS ://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value) – alfasin
你檢查了這個[鏈接](https://stackoverflow.com/questions/613183/sort-a-python-字典的值) – imanzabet
如果'RandomUserName'包含帶2個鍵的'dict',如'{'6/30/15':2,'6/30/16':3}'? – randomir