Miguel 2488
Miguel 2488

Reputation: 1440

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

Upvotes: 4

Views: 84

Answers (2)

U13-Forward
U13-Forward

Reputation: 71580

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

Upvotes: 6

yatu
yatu

Reputation: 88236

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}]

Upvotes: 8

Related Questions