我有以下词典:
d = {'d_1': {'score': 5.2, 'concept': 'a'},
'd_2': {'score': 10.1, 'concept': 'e'},
'd_3': {'score': 1.5, 'concept': 'c'},
'd_4': {'score': 20.2, 'concept': 'd'},
'd_5': {'score': 0.9, 'concept': 'b'}}
我希望按分数得到一个排序列表,如下所示:
d_sorted = [{'d_4': {'score': 20.2, 'concept': 'd'}},
{'d_2': {'score': 10.1, 'concept': 'e'}},
{'d_1': {'score': 5.2, 'concept': 'a'}},
{'d_3': {'score': 1.5, 'concept': 'c'}},
{'d_5': {'score': 0.9, 'concept': 'b'}}]
我尝试了以下内容,但这将按概念排序,而不是得分:
d_sorted = sorted(d.items(), key=operator.itemgetter(1), reverse=True)
如何将这个嵌套的dict按得分键(降序)排序到Python 2.7中的有序列表中?
编辑:这不是Sort a nested dict into an ordered list in Python 2.7的重复,因为它涉及嵌套的词组。
答案 0 :(得分:4)
首先提取值:
[{k: v} for k, v in sorted(d.items(), key=(lambda x: x[1]['score']), reverse=True)]