Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting the list of dictionaries in descending order of a particular key [duplicate]

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??

like image 728
code ninja Avatar asked Oct 18 '16 20:10

code ninja


People also ask

How do you arrange a dictionary in descending order?

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.

How do I sort a list of dictionaries by key?

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.

How do you sort a dictionary based on value descending?

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.


1 Answers

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)
like image 179
mgilson Avatar answered Nov 11 '22 18:11

mgilson