I have a list of dictionaries in python, for example
[{'a':3, 'b':4, 'c':5, 'd':'6'}, {'a':1, 'b':2, 'c':7, 'd':'9'}]
I want to sort it based on the value of 'c' in descending order. I tried using sorted()
method using key = lambda
but no help.
Any ideas??
Use dict. items() to get a list of tuple pairs from d and sort it using a lambda function and sorted(). Use dict() to convert the sorted list back to a dictionary. Use the reverse parameter in sorted() to sort the dictionary in reverse order, based on the second argument.
To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.
Sorting a dict by value descending using list comprehension. The quickest way is to iterate over the key-value pairs of your current dict and call sorted passing the dictionary values and setting reversed=True . If you are using Python 3.7, regular dict s are ordered by default.
There are lots of ways to write this. Before you're comfortable with lambdas, the best thing to do is write it out explicitly:
def sort_key(d):
return d['c']
sorted(list_of_dict, key=sort_key, reverse=True)
A trained eye will see that this is the same as the following one-liner:
sorted(list_of_dict, key=lambda d: d['c'], reverse=True)
Or, possibly:
from operator import itemgetter
sorted(list_of_dict, key=itemgetter('c'), reverse=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With