app*_*pel 2 python sorting dictionary python-2.7
我有以下意见:
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'}}
Run Code Online (Sandbox Code Playgroud)
我想按分数获取排序列表,如下所示:
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'}}]
Run Code Online (Sandbox Code Playgroud)
我尝试了以下方法,但这将按概念而不是分数进行排序:
d_sorted = sorted(d.items(), key=operator.itemgetter(1), reverse=True)
Run Code Online (Sandbox Code Playgroud)
在Python 2.7中,如何将按分数键(降序)将此嵌套字典排序为有序列表?
编辑:这不是在Python 2.7中将嵌套字典排序到有序列表中的重复,因为它涉及嵌套字典。
首先提取值:
[{k: v} for k, v in sorted(d.items(), key=(lambda x: x[1]['score']), reverse=True)]
Run Code Online (Sandbox Code Playgroud)