2012-08-01 88 views
14

如何基于嵌套字典的内部值排序Python字典?基于嵌套字典值排序Python字典

例如,整理以下mydict基础上context值:

mydict = { 
    'age': {'context': 2}, 
    'address': {'context': 4}, 
    'name': {'context': 1} 
} 

结果应该是这样的:

{ 
    'name': {'context': 1}, 
    'age': {'context': 2}, 
    'address': {'context': 4}  
} 
+1

你想要一个列表输出吗?或字典输出? – Deniz 2012-08-01 06:34:16

回答

15
>>> from collections import OrderedDict 
>>> mydict = { 
     'age': {'context': 2}, 
     'address': {'context': 4}, 
     'name': {'context': 1} 
} 
>>> OrderedDict(sorted(mydict.iteritems(), key=lambda x: x[1]['context'])) 
OrderedDict([('name', {'context': 1}), ('age', {'context': 2}), ('address', {'context': 4})]) 
5

您不能对一本字典,不管你多么努力,因为它们是无序的集合。改用OrderedDict表格collections模块。

+0

或者,也许可以在键上做一个粗糙的列表理解,使用lambda来查看每个键的值 - 这么做的困难是为什么使用OrderedDict的一个很好的教训。 – 2012-08-02 00:49:15

+0

更新:自python 3.6起,字典插入顺序被保留,所以这个语句不再是真的。 – pelson 2017-12-19 07:42:01