3

A single dictionary consists of 3 key:value pairs and I need to sort the dictionaries by comparing the first key, if the value is same the compare the second key and so on, how do I do it?

For example , if the list of dictionaries is as follows:

lst = [{'a':10,'b':20,'c':30},{'a':20,'b':50,'c':30},{'a':20,'b':40,'c':10},{'a':20,'b':40,'c':30}]

After sorting, result must be as follows:

[{'a':20,'b':50,'c':30},{'a':20,'b':40,'c':30},{'a':20,'b':40,'c':10},{'a':10,'b':20,'c':30}]

Here we can see, in the original list value of key 'a' of last 3 dictionaries was same, therefore we compared the 'b' key of them and sorted them accordingly, but 'b' key of last 2 dictionaries was same therefore we compared the 'c' key and applied the sort.

  • 3
    the dicts in your example have 3 key:value pairs, not 4. And you know that before 3.7 dicts are unordered, i.e. first, second, etc. key is ambiguous, right? – buran Sep 03 '19 at 19:40
  • 2
    this might help you: https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary?rq=1 – new Q Open Wid Sep 03 '19 at 19:47

1 Answers1

2

You could use sorted, taking the dictionary's values in the key function, that way the sorting will take place according to all values in each dictionary:

sorted(lst, key=lambda x: list(x.values()), reverse=True)

[{'a': 20, 'b': 50, 'c': 30},
 {'a': 20, 'b': 40, 'c': 30},
 {'a': 20, 'b': 40, 'c': 10},
 {'a': 10, 'b': 20, 'c': 30}]
yatu
  • 86,083
  • 12
  • 84
  • 139