Reputation: 94
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.
Upvotes: 3
Views: 50
Reputation: 88305
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}]
Upvotes: 2