16

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

Gruber
  • 2,196
  • 5
  • 28
  • 50
code ninja
  • 193
  • 1
  • 1
  • 4

2 Answers2

30

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)
mgilson
  • 300,191
  • 65
  • 633
  • 696
5
import operator
list_of_dicts.sort(key=operator.itemgetter('c'), reverse=True)
Gruber
  • 2,196
  • 5
  • 28
  • 50
Raza
  • 205
  • 1
  • 8