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}]
I guess you've meant:
This would be sorted like this:
You could use a custom comparison function, or you could pass in a function that calculates a custom sort key. That's usually more efficient as the key is only calculated once per item, while the comparison function would be called many more times.
You could do it this way:
But the standard library contains a generic routine for getting items of arbitrary objects:
itemgetter
. So try this instead:sometime we need to use
lower()
for exampleLets Say I h'v a Dictionary D with elements below. To sort just use key argument in sorted to pass custom function as below
https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions
It may look cleaner using a key instead a cmp:
or as J.F.Sebastian and others suggested,
For completeness (as pointed out in comments by fitzgeraldsteele), add
reverse=True
to sort descendingUsing Schwartzian transform from Perl,
do
gives
More on Perl Schwartzian transform