当每个字典具有不同的键时,如何按值对字典列表进行排序?

Mig*_*488 4 python sorting dictionary python-3.x pandas

我有以下字典列表:

dicts = [{'ENE001SOLC': 3},
 {'TRN002SIGN': 4},
 {'ENE001SOLC': 4, 'TRN002SIGN': 3},
 {'TRN002SIGN': 3},
 {'TRN002SOLC': 3, 'SAL016DECL': 3},
 {'ENE001SOLC': 5, 'SAL016DECL': 3},
 {'ENE001SOLC': 4}]
Run Code Online (Sandbox Code Playgroud)

我想按每个字典中的值以降序对列表进行排序(高位在前)。我已经访问过很多帖子,但是当每个字典的键值相同时,所有帖子都提供了对列表进行排序的解决方案,但事实并非如此。预期的输出将是这样的:

[{'ENE001SOLC': 5, 'SAL016DECL': 3},
{'ENE001SOLC': 4, 'TRN002SIGN': 3},
{'ENE001SOLC': 4},
{'TRN002SIGN': 4},
{'TRN002SOLC': 3, 'SAL016DECL': 3},
{'ENE001SOLC': 3},
{'TRN002SIGN': 3}]
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点??任何帮助都感激不尽。

提前非常感谢你

yat*_*atu 8

您可以sorted根据在内部词典的值中找到的最大值来使用和排序列表:

from operator import itemgetter

sorted(dicts, key=lambda x: max(x.values()), reverse=True)

[{'ENE001SOLC': 5, 'SAL016DECL': 3},
 {'TRN002SIGN': 4},
 {'ENE001SOLC': 4, 'TRN002SIGN': 3},
 {'ENE001SOLC': 4},
 {'ENE001SOLC': 3},
 {'TRN002SIGN': 3},
 {'SAL016DECL': 3, 'TRN002SOLC': 3}]
Run Code Online (Sandbox Code Playgroud)


U10*_*ard 6

尝试使用此sorted命令,排序器将是该值的最大值,为什么我需要-,所以我将数字设为负数,如果不这样做,则该顺序将由低到高:

print(sorted(dicts, key=lambda x: -max(x.values())))
Run Code Online (Sandbox Code Playgroud)

对于大熊猫,Series请执行以下操作:

dicts = dicts.to_frame()
dicts[1] = dicts[0].apply(lambda x: -max(x.values()))
dicts = dicts.sort_values(1)
print(dicts[0])
Run Code Online (Sandbox Code Playgroud)

输出:

5    {'ENE001SOLC': 5, 'SAL016DECL': 3}
1                     {'TRN002SIGN': 4}
2    {'ENE001SOLC': 4, 'TRN002SIGN': 3}
6                     {'ENE001SOLC': 4}
0                     {'ENE001SOLC': 3}
3                     {'TRN002SIGN': 3}
4    {'TRN002SOLC': 3, 'SAL016DECL': 3}
Name: 0, dtype: object
Run Code Online (Sandbox Code Playgroud)