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?

Recommended Answers

All 4 Replies

use key parameter with lambda statement or functools.partial or helper function.

Convert to a list of lists with highest score first, then time, then name. Or take a look at "Complex Sorts" in the Howto Sorting

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:')

# 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:')

''' 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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.