Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order a list of dictionaries by value when each dictionary has a different key?

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

like image 619
Miguel 2488 Avatar asked Dec 07 '22 11:12

Miguel 2488


2 Answers

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}]
like image 196
yatu Avatar answered Dec 11 '22 11:12

yatu


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
like image 40
U12-Forward Avatar answered Dec 11 '22 12:12

U12-Forward