Python Person
Python Person

Reputation: 13

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:

from collections import OrderedDict
#opens the class file in order to create a dictionary
dictionary = {}
#splits the data so the name is the key while the score is the value
f = open('ClassA.txt', 'r')
d = {}
for line in f:
    firstpart, secondpart = line.strip().split(':')
    dictionary[firstpart.strip()] = secondpart.strip()
    columns = line.split(": ")
    letters = columns[0]
    numbers = columns[1].strip()
    if d.get(letters):
        d[letters].append(numbers)
    else:
        d[letters] = list(numbers)
#sorts the dictionary so it has a alphabetical order
sorted_dict = OrderedDict(sorted(d.items()))
print (sorted_dict)

And the problem I encountered is when trying to print the dictionary with the names and the scores from highest to lowest is that it will either only print the name with the highest score when using the max function or if im using the itemgetter it only seems to work for lowest to highes. So I was wondering if anyone would be able to help me out. Anything is appreciated, explain it if possible :)

Upvotes: 2

Views: 6437

Answers (2)

Kolmar
Kolmar

Reputation: 14224

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])])

Upvotes: 3

agconti
agconti

Reputation: 18093

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)])

Upvotes: 2

Related Questions