-1

I have a list of the dictionary as follows:

[{"A":5,"B":10},

{"A":6,"B":13},

{"A":10,"B":5}]

I want to this list in decending order on the value of B. The output should look like this:

[{"A":6,"B":13},

{"A":5,"B":10},

{"A":10,"B":5}]

How to do that?

a b
  • 67
  • 1
  • 4
  • I think this URL can help https://stackoverflow.com/questions/1143671/how-to-sort-objects-by-multiple-keys-in-python – vasadia Jun 23 '21 at 15:46
  • Does this answer your question? [How do I sort a list of dictionaries by a value of the dictionary?](https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary) – Pranav Hosangadi Jun 23 '21 at 15:49

1 Answers1

2

You can sort lists by the results of applying a function to each element: https://docs.python.org/3.9/library/functions.html#sorted

>>> data = [{"A":5,"B":10},
...     {"A":6,"B":13},
...     {"A":10,"B":5}]
>>> sorted(data, key=lambda dct: dct["B"], reverse=True)
[{'A': 6, 'B': 13}, {'A': 5, 'B': 10}, {'A': 10, 'B': 5}]
ForceBru
  • 43,482
  • 10
  • 63
  • 98