【问题标题】:Sorting by nested dictionary in Python dictionary在 Python 字典中按嵌套字典排序
【发布时间】:2015-11-12 22:17:31
【问题描述】:

我有以下结构

{
    '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)

【问题讨论】:

标签: python python-2.7 sorting dictionary


【解决方案1】:

您可以简单地使用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}]}

【讨论】:

    【解决方案2】:

    您可以对列表进行排序并在字典中覆盖自身。

    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)
    

    【讨论】:

      【解决方案3】:

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

      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)
      

      【讨论】:

        猜你喜欢
        • 2021-07-27
        • 1970-01-01
        • 2014-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-17
        相关资源
        最近更新 更多