Sort a Python list by dictionary key

By on May 5th, 2010 in Python Comments (4)

I probably should have known how to do this innately, it’s that simple, but I didn’t. So for the benefit of fellow feckless Pythonistas, here is how to sort a list of dictionaries based on a key in the dictionary.

Say I have a list of dictionaries where each dictionary represents data for a person who has a unique ID, so the list looks like this:

1
peeps = [{'id':'1', 'name':'Christine'}, {'id':'2', 'name':'Steve'}]

To sort by id:

1
peeps.sort(key=lambda peep: peep['id'])

TA DA!!!!!!!! Pretty impressive, right? Not really :) But here’s a wonderful article on Python sorting to make up for my unimpressiveness. Stay tuned, next week we’ll be learning to tie our shoes!


  • Rizwan Kassim

    You can also use operator.itemgetter\
    And be aware of OrderedDict

  • Christine Meranda

    Hey thanks Riz!!! :)

  • Rizwan Kassim

    No problem. Your username is still admin, btw. =)

  • Christine Meranda

    Dammit, you’re right! Ah well.