Python字典中的嵌套字典排序
我有以下结构Python字典中的嵌套字典排序,python,python-2.7,sorting,dictionary,Python,Python 2.7,Sorting,Dictionary,我有以下结构 { 'searchResult' : [{ 'resultType' : 'station', 'ranking' : 0.5 }, { 'resultType' : 'station', 'ranking' : 0.35 }, { 'resultType' : 'station', 'ranking
{
'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)
你只需对列表进行排序,然后在字典中重新填写即可
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)
您只需使用
key=itemgetter(“排名”)
和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}]}
谢谢大家!但是哪个方法更快呢?
d[“item”].sort()
还是sorted()
?可能重复的@SpanishBoysorted
会返回一个新对象。如果您不需要原始对象,最好坚持使用排序
,以提高速度和内存效率。