基于嵌套字典值排序Python字典 [英] Sorting Python dictionary based on nested dictionary values
本文介绍了基于嵌套字典值排序Python字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何根据嵌套字典的内在值排序Python字典?
例如,排序 mydict
以下$ code>上下文的价值:
mydict = {
'age':{'context':2},
'address':{'context':4},
'name':{'context':1}
}
结果应该是这样的:
{
'name':{'context':1},
'age':{'context':2},
'地址':{'上下文':4}
}
解决方案
>>>从集合导入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}), ',{'context':2}),('address',{'context':4})])
How do you sort a Python dictionary based on the inner value of a nested dictionary?
For example, sort mydict
below based on the value of context
:
mydict = {
'age': {'context': 2},
'address': {'context': 4},
'name': {'context': 1}
}
The result should be like this:
{
'name': {'context': 1},
'age': {'context': 2},
'address': {'context': 4}
}
解决方案
>>> 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})])
这篇关于基于嵌套字典值排序Python字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文