Python: Sort a list of dicts by dict-key
I always forget that one and end up searching for half an hour:
PYTHON:
-
>>> list = [ dict(a=1,b=2,c=3),
-
... dict(a=2,b=2,c=2),
-
... dict(a=3,b=2,c=1)]
-
>>> list.sort(key=operator.itemgetter('c'))
-
>>> list
-
[{'a': 3, 'c': 1, 'b': 2}, {'a': 2, 'c': 2, 'b': 2}, {'a': 1, 'c': 3, 'b': 2}]
-
>>> list.sort(key=operator.itemgetter('a'))
-
>>> list
-
[{'a': 1, 'c': 3, 'b': 2}, {'a': 2, 'c': 2, 'b': 2}, {'a': 3, 'c': 1, 'b': 2}]
sorry, this piece of code doesn't work for me...
python says
NameError: name 'operator' is not defined
Thanks for this!
Sean - don't forget to "import operator"
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.