-3

I have a list which looks like this:

some_list = [{'id':1, 'name':'Steve', 'age':23}, {'id':2, 'name':'John', 'age':17}, {'id':3, 'name':'Matt', 'age':31}]

I would like to sort the list my the name value in the dictionary. So Instead of the above order, it would be John then Matt then Steve.

How would I go about this? Thanks.

Pav Sidhu
  • 6,724
  • 18
  • 55
  • 110

1 Answers1

0

You can use operator.itemgetter:

>>> import operator
>>> some_list = [dict(id=1, name='Steve', age=23), dict(id=2, name='John', age=17), dict(id=3, name='Matt', age=31)]
>>> sorted(some_list, key=operator.itemgetter('name'))
[{'id': 2, 'age': 17, 'name': 'John'}, {'id': 3, 'age': 31, 'name': 'Matt'}, {'id': 1, 'age': 23, 'name': 'Steve'}]

Or a lambda function:

>>> some_list = [dict(id=1, name='Steve', age=23), dict(id=2, name='John', age=17), dict(id=3, name='Matt', age=31)]
>>> sorted(some_list, key=lambda x: x['name'])
[{'id': 2, 'age': 17, 'name': 'John'}, {'id': 3, 'age': 31, 'name': 'Matt'}, {'id': 1, 'age': 23, 'name': 'Steve'}]
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97