Reputation: 53
related to a previous question, I have a dictionary within a list which I need to sort. The code is:
dict1 = [{"Name":"Ron","one":3,"two":6,"three":10}
,{"Name":"Mac","one":5,"two":8,"three":0}
,{"Name":"DUDE","one":16,"two":9,"three":2}]
I would like to so when I print out the dictionary, it will print out the name of the person with the highest score, then the name of the person with the second highest score, then the name with the third highest score etc. The intended output for this particular list is: DUDE 16 #as DUDE's highest score is 16, and 16 is the highest high score Ron 10 #as Ron's highest score is 10, but it is the second highest high score Mac 8#as Mac's highest score is 8, but his high score is the least highest high score out of the three of them.
Any help would be much appreciated.
Upvotes: 1
Views: 162
Reputation: 7057
Something like this?:
print [(x["Name"] + " " + str(max(x["one"],x["two"],x["three"])) ) for x in sorted(dict1, key=lambda row: max(row["one"],row["two"],row["three"]),reverse=True )]
>>> ['DUDE 16', 'Ron 10', 'Mac 8']
This essentially uses the maximum of all three values as a sorting key, and places them in reverse. Then it prints out the name and this maximum value in a list comprehension statement.
Upvotes: 2