gpt4 book ai didi

python - 按Python字典中的嵌套字典排序

转载 作者:太空狗 更新时间:2023-10-30 00:31:43 25 4
gpt4 key购买 nike

我有以下结构

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

关于python - 按Python字典中的嵌套字典排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32098479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com