繁体   English   中英

在Python字典中按嵌套字典排序

[英]Sorting by nested dictionary in Python dictionary

我有以下结构

{
    'searchResult' : [{
            'resultType' : 'station',
            'ranking' : 0.5
        }, {
            'resultType' : 'station',
            'ranking' : 0.35
        }, {
            'resultType' : 'station',
            'ranking' : 0.40
        }
    ]
}

并希望得到

{
    'searchResult' : [{
            'resultType' : 'station',
            'ranking' : 0.5
        }, {
            'resultType' : 'station',
            'ranking' : 0.4
        }, {
            'resultType' : 'station',
            'ranking' : 0.35
        }
    ]
}

尝试了代码没有成功

result = sorted(result.items(), key=lambda k: k[1][0][1]["ranking"], reverse=True)

如果您可以就地更改对象。

a = {
    'searchResult' : [{
                       'resultType' : 'station',
                       'ranking' : 0.5
                      }, {
                       'resultType' : 'station',
                       'ranking' : 0.35
                      }, {
                      'resultType' : 'station',
                      'ranking' : 0.40
                      }]
  }

a["searchResult"].sort(key=lambda d: d["ranking"], reverse=True)

或者你可以制作一份深层拷贝以保留原件

from copy import deepcopy


srt_dict = deepcopy(a)
srt_dict["searchResult"].sort(key=lambda d: d["ranking"], reverse=True)

您可以使用key=itemgetter("ranking")reverse=True在列表上进行原位排序:

from operator import itemgetter
d["searchResult"].sort(key=itemgetter("ranking"),reverse=True)

print(d)
{'searchResult': [{'resultType': 'station', 'ranking': 0.5}, {'resultType': 'station', 'ranking': 0.4}, {'resultType': 'station', 'ranking': 0.35}]}

您可以对列表进行排序并在字典中自行编写。

result = {
    'searchResult' : [{
            'resultType' : 'station',
            'ranking' : 0.5
        }, {
            'resultType' : 'station',
            'ranking' : 0.35
        }, {
            'resultType' : 'station',
            'ranking' : 0.40
        }
    ]
}

result['searchResult'] = sorted(result['searchResult'], key= lambda x: x['ranking'], reverse=True)

暂无
暂无

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

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