12

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
  • 1,750
  • 4
  • 22
  • 42
code ninja
  • 153
  • 1
  • 1
  • 4

2 Answers2

25

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
  • 264,617
  • 51
  • 541
  • 636
4
import operator
list_of_dicts.sort(key=operator.itemgetter('c'), reverse=True)
Gruber
  • 1,750
  • 4
  • 22
  • 42
Raza
  • 195
  • 1
  • 8