[英]Sorting by nested dictionary in Python dictionary
I have below structure 我有以下结构
{
'searchResult' : [{
'resultType' : 'station',
'ranking' : 0.5
}, {
'resultType' : 'station',
'ranking' : 0.35
}, {
'resultType' : 'station',
'ranking' : 0.40
}
]
}
and want to get 并希望得到
{
'searchResult' : [{
'resultType' : 'station',
'ranking' : 0.5
}, {
'resultType' : 'station',
'ranking' : 0.4
}, {
'resultType' : 'station',
'ranking' : 0.35
}
]
}
Tried the code without success 尝试了代码没有成功
result = sorted(result.items(), key=lambda k: k[1][0][1]["ranking"], reverse=True)
If you are okay with changing the objects in-place. 如果您可以就地更改对象。
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)
Or you can make a deep copy to keep the original 或者你可以制作一份深层拷贝以保留原件
from copy import deepcopy
srt_dict = deepcopy(a)
srt_dict["searchResult"].sort(key=lambda d: d["ranking"], reverse=True)
You can simply do an inplace sort on the list, using key=itemgetter("ranking")
and 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}]}
You can just sort the list and write over itself in the dictionary. 您可以对列表进行排序并在字典中自行编写。
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.