Varun Varun - 3 months ago 12
Python Question

How do I sort a dictionary in decreasing order based on values of the list as its value?

I have a dictionary as below:

{'Muguruza': [0, 0, 1, 12, 2, 15], 'Williams': [0, 1, 2, 15, 1, 12], 'Murray': [2, 2, 16, 143, 13, 142], 'Djokovic': [3, 1, 13, 142, 16, 143]}


I want to sort it in decreasing order based on the values in the corresponding list.

I have to print out to the screen a summary in decreasing order of ranking, where the ranking is according to the criteria 1-6(as given in the list) in that order (compare item 1, if equal compare item 2, if equal compare item 3 etc, noting that for items 5 and 6 the comparison is reversed).

My output should be as below:

Djokovic 3 1 13 142 16 143
Murray 2 2 16 143 13 142
Williams 0 1 2 15 1 12
Muguruza 0 0 1 12 2 15


Here Williams and Murray had same value for element at index 0 of the list so they are compared on the basis of value at the next index in the list.

How can I do this in Python?

Answer

You can just compare python list with > < =. Simple as that. It will do the exact same thing as you want. Also operator is a great way to sort dicts based on values

dict = {'Muguruza': [0, 0, 1, 12, 2, 15], 'Williams': [0, 1, 2, 15, 1, 12], 'Murray': [2, 2, 16, 143, 13, 142], 'Djokovic': [3, 1, 13, 142, 16, 143]}
import operator
print(sorted(dict.items(), key=operator.itemgetter(1)))

for i in sorted_list:
    print(i[0], " ".join([str(j) for j in i[1]]))

Returns

Williams 0 1 2 15 1 12
Murray 2 2 16 143 13 142
Djokovic 3 1 13 142 16 143
Muguruza 9 0 1 12 2 15
Comments