You can use python's built-in functions sort()
or sorted()
where sort()
method will sort the list in-place, and sorted()
will return a new sorted list in case you don't need the original list. both sort()
and sorted()
have a key
parameter that specify a callable which will be called on each list's element for comparisons. for more details, see docs
if we say that your list for example look like this:
>>> list_name_second = [
{'Name': 'Malcolm', 'percentage': 50.0},
{'Name': 'Sam', 'percentage': 30.0},
{'Name': 'Ru', 'percentage': 100.0},
{'Name': 'Kam', 'percentage': 10.0},
{'Name': 'Joe', 'percentage': 20.0}
]
so, you can sort your list in-place
based on percentage
key of dict
list element using sort(key=callable)
like follows:
>>> list_name_second.sort(key=lambda d: d['percentage'])
>>> list_name_second
[{'Name': 'Kam', 'percentage': 10.0}, {'Name': 'Joe', 'percentage': 20.0}, {'Name': 'Sam', 'percentage': 30.0}, {'Name': 'Malcolm', 'percentage': 50.0}, {'Name': 'Ru', 'percentage': 100.0}]
or, you can use sorted(key=callable)
which it will return a new sorted list, like follows:
>>> sorted(list_name_second, key=lambda d: d['percentage'])
[{'Name': 'Kam', 'percentage': 10.0}, {'Name': 'Joe', 'percentage': 20.0}, {'Name': 'Sam', 'percentage': 30.0}, {'Name': 'Malcolm', 'percentage': 50.0}, {'Name': 'Ru', 'percentage': 100.0}]
here, you are passing a callable lambda function to be applied on each element of the list, which its extract the 'percentage'
key's value from the dict
and return it to sort
or sorted
built-in functions to be used as reference for sorting process.
Note:
if your elements in the list look like this: [{'Name': 'Malcolm', 'percentage': '50.0'}]
, where 'percentage'
's value is a string, you have to cast its value to compared as a float, like this:
>>> list_name_second = [
{'Name': 'Malcolm', 'percentage': '50.0'},
{'Name': 'Sam', 'percentage': '30.0'},
{'Name': 'Ru', 'percentage': '100.0'},
{'Name': 'Kam', 'percentage': '10.0'},
{'Name': 'Joe', 'percentage': '20.0'}
]
>>> sorted(list_name_second, key=lambda d: float(d['percentage']))
[{'Name': 'Kam', 'percentage': '10.0'}, {'Name': 'Joe', 'percentage': '20.0'}, {'Name': 'Sam', 'percentage': '30.0'}, {'Name': 'Malcolm', 'percentage': '50.0'}, {'Name': 'Ru', 'percentage': '100.0'}]