Skip to content Skip to sidebar Skip to footer

How To Sort A Dictionary To Print From Highest Value To Lowest For Each Key?

txt would contain a something like this: Matt Scored: 10 Jimmy Scored: 3 James Scored: 9 Jimmy Scored: 8 .... The code I managed to put together (quite new to python) is here: fro

Solution 1:

You can use this:

sorted_dict = OrderedDict(
    sorted((key, list(sorted(vals, reverse=True))) 
           for key, vals in d.items()))

This snippet sorts the names in alphabetic order and the scores for each name from highest to lowest. The reverse parameter in sort methods can be used to force the order from highest to lowest.

For example:

>>> d = {"Matt": [2,1,3], "Rob": [4,5]}
>>> OrderedDict(sorted((key, list(sorted(vals, reverse=True))) for key, vals in d.items()))
OrderedDict([('Matt', [3, 2, 1]), ('Rob', [5, 4])])

Solution 2:

You can use an OrderedDict:

# regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

# dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

Post a Comment for "How To Sort A Dictionary To Print From Highest Value To Lowest For Each Key?"