Skip to content

Rank sort a list of dictionaries based on a value in Python

Advertisements
[{'name_html': 's', 'mkc': 1, 'kills': 14, 'deaths': 4, 'lastCharacter': 'Spaz', 'lastName': 's', 'games': 3, 'scores': 439, 'aid': 'pb - IF4JVRcuLA == '}, {'name_html': 'Android48457626', 'mkc': 0, 'kills': 0, 'deaths': 6, 'lastCharacter': 'Kronk', 'lastName': 'peo', 'games': 3, 'scores': 205, 'aid': 'pb - IF4rVWseCg == '}]

Let’s take the list of dictionaries above as an example. I’d like to sort this list based on the scores value. To do this we can use the sorted() function

rank sort list dictionariesrank_sorted = sorted(res, key=lambda x: x['scores'])
print(rank_sorted)
#[{'name_html': 'Android48457626', 'mkc': 0, 'kills': 0, 'deaths': 6, 'lastCharacter': 'Kronk', 'lastName': 'peo', 'games': 3, 'scores': 205, 'aid': 'pb - IF4rVWseCg == '}, {'name_html': 's', 'mkc': 1, 'kills': 14, 'deaths': 4, 'lastCharacter': 'Spaz', 'lastName': 's', 'games': 3, 'scores': 439, 'aid': 'pb - IF4JVRcuLA == '}]

This is how I did it.

See also  Remove duplicates from a list in Python

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.