Tag Archives: itemgetter

Sort a list of dictionaries by a key In all of them

If you have a list of dictionaries like this:

fruit = [{'Name': 'Banana', 'Colour': 'Yellow', 'Shape': 'Bent'},
            {'Name': 'Apple', 'Colour': 'Red', 'Shape': 'Round'}]

And you want to sort them by the Name key, you can do one of two things.

Method 1: Use a lambda

print sorted(fruit, key=lambda k: k['Name'])

Method 2: Use itemgetter

from operator import itemgetter
print sorted(fruit, key=itemgetter('Name'))