The sorted() function takes a key= parameter
newlist = sorted(list_to_be_sorted, key=lambda d: d['name'])
Alternatively, you can use operator.itemgetter instead of defining the function yourself
from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))
For completeness, add reverse=True to sort in descending order
newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True)
Answer from Mario F on Stack OverflowThe sorted() function takes a key= parameter
newlist = sorted(list_to_be_sorted, key=lambda d: d['name'])
Alternatively, you can use operator.itemgetter instead of defining the function yourself
from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))
For completeness, add reverse=True to sort in descending order
newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True)
import operator
To sort the list of dictionaries by key='name':
list_of_dicts.sort(key=operator.itemgetter('name'))
To sort the list of dictionaries by key='age':
list_of_dicts.sort(key=operator.itemgetter('age'))
How to sort a list containing dictionary items?
Sorting a dict by its values
Lists, dictionaries,tuple, sort,
How to sort a list of dictionaries where the keys are strings and some of them are either empty or don't exist
Let's say i have a list from a json like this:
list = [
{
"name": "Player1",
"currency": "10"
},
{
"name": "Player2",
"currency": "15"
},
{
"name": "Player3",
"currency": "7"
}]
How do i sort it based on the amount of currency a player has so that i can get the richest players using simple list indexes? For example if i want the details of the second richest player, i sort the list based on the amount of currency player has and then do a simple list[1] to get their details. How do i achieve this?
I have a list of dictionaries coming from a rest API,
myList = [
{ 'id' : 1, 'rating' : "14" },
{ 'id': 2},
{ 'id': 3, 'rating': "" },
{ 'id': 4, 'rating': "20.1"}
]I'm trying to sort it by key="rating"
sorted_list = sorted(dict_list, key=lambda d: float(d[key]), reverse=True)
I'm getting this error
TypeError: string indices must be integers
This is because the rating is either empty or sometimes nonexistent. In that case how to make the rating=0 so that the sorting works?