Archive for July, 2007

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}]