简体   繁体   English

基于嵌套字典值对 Python 字典进行排序

[英]Sorting Python dictionary based on nested dictionary values

How do you sort a Python dictionary based on the inner value of a nested dictionary?如何根据嵌套字典的内部值对 Python 字典进行排序?

For example, sort mydict below based on the value of context :例如,根据context的值对下面的mydict排序:

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})])

You can not sort a dictionary no matter how hard you try, because they are an unordered collection. 无论您如何努力,都无法对字典进行排序,因为它们是无序的集合。 Use OrderedDict form collections module instead. 请改用OrderedDict表单collections模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM