Hi, I'm learning python and I'm having a bit of a problem sorting dictionaries. I'm getting dictionaries that look something like this:

{'usain': [2, 52], 'tyson': [1, 11], 'carl': [3, 110]}

which follows the format {'name': [score,time]}. I want to get a list of the names sorted by the highest scores (and if there's a tie the one who has a shorter time should come first). I'm not really sure how to go about this. Any suggestions?

You can sort by two criteria this way ...

import operator as op

# a test dictionary with name:[age,weight] pairs
mydict = {
'Zack' : [35, 210],
'Adam' : [24, 175],
'John' : [35, 150],
'Tony' : [35, 244]
}

# convert to list of (name, age, weight) tuples
mylist = []
for name, sublist in mydict.items():
    age, weight = sublist
    mylist.append((name, age, weight))

print('original list of (name, age, weight) tuples:')
print(mylist)

# sort tuples by age at index 1, and weight at index 2
mylist_age_weight = sorted(mylist, key=op.itemgetter(1, 2))

print('sorted by age and weight:')
print(mylist_age_weight)

''' result ...
original list of (name, age, weight) tuples:
[('Tony', 35, 244), ('John', 35, 150), ('Zack', 35, 210), ('Adam', 24, 175)]
sorted by age and weight:
[('Adam', 24, 175), ('John', 35, 150), ('Zack', 35, 210), ('Tony', 35, 244)]
'''

But you require a mixed reverse condition, for that you will have to use a helper function.

This question has already been answered. Start a new discussion instead.