DEV Community

Discussion on: How to Sort a List of Dictionaries in Python

Collapse
 
dmitrypolo profile image
dmitrypolo • Edited

You don't need to use lambda here at all. In fact you would be better off using itemgetter from the operator module in the standard library.

from operator import itemgetter

f = itemgetter('Name')
csv_mapping_list.sort(key=f)

[{'Name': 'Ally', 'Age': 41, 'Favorite Color': 'Magenta'},
 {'Name': 'Jasmine', 'Age': 29, 'Favorite Color': 'Aqua'},
 {'Name': 'Jeremy', 'Age': 25, 'Favorite Color': 'Blue'}]
Collapse
 
renegadecoder94 profile image
Jeremy Grifski • Edited

Define "better off." Using itemgetter is definitely another way to do it, but it's almost exactly the same as the lambda option. Likewise, I could have also written a function of my own to pass as the key.

Of course, I'm happy to add itemgetter as another option if you want.

EDIT: I added your example to the article.

Collapse
 
dmitrypolo profile image
dmitrypolo

itemgetter is faster than using lambda specifically because all the operations are performed on the C side. I should have clarified when I made my response. Thanks for the shoutout!

Thread Thread
 
renegadecoder94 profile image
Jeremy Grifski • Edited

Thanks for the clarification! I wasn't aware of that. The article has been updated to include a note about performance.