Sort a Python list by dictionary key
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
-
Christine Meranda
-
Rizwan Kassim
-
Christine Meranda