I have a list of dictionaries and want each item to be sorted by a specific property values.
Take into consideration the array below,
[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
When sorted by name
, should become
[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]
Here is the alternative general solution - it sorts elements of dict by keys and values. The advantage of it - no need to specify keys, and it would still work if some keys are missing in some of dictionaries.
I tried something like this:
It worked for integers as well.
'key' is used to sort by an arbitrary value and 'itemgetter' sets that value to each item's 'name' attribute.
my_list
will now be what you want.(3 years later) Edited to add:
The new
key
argument is more efficient and neater. A better answer now looks like:...the lambda is, IMO, easier to understand than
operator.itemgetter
, but YMMV.Using the pandas package is another method, though it's runtime at large scale is much slower than the more traditional methods proposed by others:
Here are some benchmark values for a tiny list and a large (100k+) list of dicts: