3

This thread How do I sort a list of dictionaries by values of the dictionary in Python? explains very clearly how to sort a list of dictionaries. In summary for,

[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]

You do:

newlist = sorted(list_to_be_sorted, key=lambda k: k['name']) 

However, I have much more elements in my dictionary and I need to sort by four of them - not just one. Any tips how to do this?

Note: I read further into the thread and this suggestion:

sortedlist = sorted(input, key=lambda elem: "%02d %s" % (elem['age'], elem['name']))

does not work. It gives error:

TypeError: list indices must be intergers, not str

I try various versions of this and to no avail.

Any help appreciated,

2
  • That actually works for me. Are you sure you set input to [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]? [Although I'd sort by the tuple itself, rather than the string. Simpler and less error-prone-- say there's a 100-year-old.]
    – DSM
    Jan 29, 2012 at 18:47
  • Very good doc at Python Wiki: Sorting Mini-HOW TO
    – reclosedev
    Jan 29, 2012 at 18:53

1 Answer 1

4

Simply change the key function to return a tuple containing the elements you wish to sort by:

newlist = sorted(input, key=lambda k: (k['age'], k['name'])) 

For example:

In [13]: input = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}, {'name':'Milhouse', 'age':10}, {'name': 'Mr. Burns', 'age': 104}]

In [14]: sorted(input, key=lambda k: (k['age'], k['name']))
Out[14]: 
[{'age': 10, 'name': 'Bart'},
 {'age': 10, 'name': 'Milhouse'},
 {'age': 39, 'name': 'Homer'},
 {'age': 104, 'name': 'Mr. Burns'}]

Your approach with string formatting could also be made to work, but the number of digits in the format would need to be increased to accommodate the likes of Cornelius Chapman. ;-)

Having said that, I would recommend using a tuple, as this tackles the problem more directly, is more efficient and is less prone to coding errors.

edit: As suggested by @JBernardo in the comments, the above can also be phrased using operator.itemgetter():

In [19]: sorted(input, key=operator.itemgetter('age','name'))
Out[19]: 
[{'age': 10, 'name': 'Bart'},
 {'age': 10, 'name': 'Milhouse'},
 {'age': 39, 'name': 'Homer'},
 {'age': 104, 'name': 'Mr. Burns'}]
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.