簡體   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