1

I'm been thiking of a method for sorting a list without labels and only numbers, like [{1:2},{3:3},{4:5},{6:10}] by it's values but I can't come up with a solution. The method should be like this.

Input:[{1:2},{3:3},{4:5},{6:10}]

Output: [{6:10},{4:5},{3:3},{1:2}]

Can someone help?

Enzo Massaki
  • 301
  • 1
  • 10

1 Answers1

2

Use a regular sort or sorted, with a key that uses whatever aggregation of the values you want to sort on (since a dict might have multiple values). For example:

>>> x = [{1:2},{3:3},{4:5},{6:10}]
>>> sorted(x, key=lambda d: -sum(d.values()))
[{6: 10}, {4: 5}, {3: 3}, {1: 2}]

Alternatives to sum might include:

  • next (if you're very confident that each dict has exactly one value)
  • statistics.mean (if they might have varying numbers of values and you want the average)
  • statistics.mode (if you want the most frequent value in each dict)

etc

Samwise
  • 68,105
  • 3
  • 30
  • 44