I have the following list of dicts:
dicts = [{'ENE001SOLC': 3},
{'TRN002SIGN': 4},
{'ENE001SOLC': 4, 'TRN002SIGN': 3},
{'TRN002SIGN': 3},
{'TRN002SOLC': 3, 'SAL016DECL': 3},
{'ENE001SOLC': 5, 'SAL016DECL': 3},
{'ENE001SOLC': 4}]
I want to sort this list by the values in each dict in descending order (higher comes first). I have visited a lot of posts already but all of them provide solution to sort the list when the values of the keys are the same for each dict, but this is not the case. The expected output would be somethinglike this:
[{'ENE001SOLC': 5, 'SAL016DECL': 3},
{'ENE001SOLC': 4, 'TRN002SIGN': 3},
{'ENE001SOLC': 4},
{'TRN002SIGN': 4},
{'TRN002SOLC': 3, 'SAL016DECL': 3},
{'ENE001SOLC': 3},
{'TRN002SIGN': 3}]
How can i do this?? Any help will be much appreciated.
Thank you very much in advance
You could use sorted
and order the lists according to the maximum value found in the inner dictionaries' values:
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}]
Try using this sorted
command and the sorter will be the maximum of the value, why do I need -
, so I make the number negative, if I don't the order will be low to high:
print(sorted(dicts, key=lambda x: -max(x.values())))
For a pandas Series
do:
dicts = dicts.to_frame()
dicts[1] = dicts[0].apply(lambda x: -max(x.values()))
dicts = dicts.sort_values(1)
print(dicts[0])
Output:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With