1

I have a list with individual items as dictionaries which might have different keys. I want to sort them based on the values. E.g.

Lets say,

unsorted_list = [{'a': 23}, {'b': 34}, {'c': 2}]

After sort, (descending)

sorted_list = [{'b': 34}, {'a': 23}, {'c': 2}]

Please let me how to do it in python

martineau
  • 112,593
  • 23
  • 157
  • 280
  • 3
    Folks: This is not a duplicate of any of those. The question is about sorting a list that contains dictionaries (by the contents of the dictionaries). – martineau Oct 13 '17 at 14:56
  • This question is slightly different in the case that here each item in the list is a dict. Also keys are different for different dicts. – Kanhaiya Choudhary Oct 13 '17 at 14:56

3 Answers3

2

you need to sort the elements according to the dict values (there is only one value anyway), in reverse:

unsorted_list = [{'a': 23}, {'b': 34}, {'c': 2}]

sorted_list = sorted(unsorted_list, key = lambda d : list(d.values()), reverse=True)

result:

[{'b': 34}, {'a': 23}, {'c': 2}]
Jean-François Fabre
  • 131,796
  • 23
  • 122
  • 195
1

You can try this:

unsorted_list = [{'a': 23}, {'b': 34}, {'c': 2}]
final_data = sorted(unsorted_list, key=lambda x:x.values()[0])[::-1]

Output:

[{'b': 34}, {'a': 23}, {'c': 2}]
Ajax1234
  • 66,333
  • 7
  • 57
  • 95
  • 1
    You should pass the `reverse=True` keyword to `sorted()` instead of the having the `[::-1]` at the end. – martineau Oct 13 '17 at 15:11
0

This should do what you need:

sorted_list = sorted(unsorted_list, key=lambda x: list(x.values())[0]*-1)

or

sorted_list = sorted(unsorted_list, key=lambda x: list(x.values())[0], reverse=True)
zipa
  • 26,044
  • 6
  • 38
  • 55