Python: Sort a list of dicts by dict-key

I always forget that one and end up searching for half an hour:

PYTHON:
  1. >>> list = [ dict(a=1,b=2,c=3),
  2. ...   dict(a=2,b=2,c=2),
  3. ...   dict(a=3,b=2,c=1)]
  4. >>> list.sort(key=operator.itemgetter('c'))
  5. >>> list
  6. [{'a': 3, 'c': 1, 'b': 2}, {'a': 2, 'c': 2, 'b': 2}, {'a': 1, 'c': 3, 'b': 2}]
  7. >>> list.sort(key=operator.itemgetter('a'))
  8. >>> list
  9. [{'a': 1, 'c': 3, 'b': 2}, {'a': 2, 'c': 2, 'b': 2}, {'a': 3, 'c': 1, 'b': 2}]

3 Comments

  1. sean Says:

    sorry, this piece of code doesn't work for me...
    python says

    NameError: name 'operator' is not defined

  2. Josh Says:

    Thanks for this!

    Sean - don't forget to "import operator"

  3. Rob Says:

    You could also use "list.sort(lambda x, y: cmp(x['c'], y['c']))". BTW, you're shadowing (I think that's the right term) the built-in definition of list([sequence]) as a constructor for lists.

Leave a Reply