您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

5b51 2022/1/14 8:20:28 python 字数 1623 阅读 458 来源 www.jb51.cc/python

我有以下结构 { 'searchResult' : [{ 'resultType' : 'station', 'ranking' : 0.5 }, { 'resultType' : 'station', 'ranking' : 0.35 }, {

概述

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

并希望得到

{
    'searchResult' : [{
            'resultType' : 'station','ranking' : 0.4
        },'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)

总结

以上是编程之家为你收集整理的在Python字典中按嵌套字典排序全部内容,希望文章能够帮你解决在Python字典中按嵌套字典排序所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶