Christian
Christian

Reputation: 1586

How to pythonicly create a dictionary of highscores from a list of scores

In python, assume I have a list of key-value pairs of player names and scores like this:

[
    ('ABC', 129),
    ('JON', 205),
    ('DON', 90),
    ('ABC', 300),
    ('DON', 50)
]

From this list I want to extract a highscore dictionary like this:

{
    'ABC': 300,
    'DON': 90,
    'JON': 205,
}

Bonus-Question: How could I create a dictionary of a score history like this and maintain the order of each score-occurence from the original list?

{
    'ABC': [129, 300]
    'DON': [90, 50]
    'JON': [205]
}

Obviously it is pretty easy to implement the solution with a for-loop, but what is the most pythonic way, i.e. how can it be done with list/dictionary comprehension?

Upvotes: 0

Views: 252

Answers (2)

alexis
alexis

Reputation: 50218

The second part is a pretty standard thing to do:

allscores = [
    ('ABC', 129),
    ('JON', 205),
    ('DON', 90),
    ('ABC', 300),
    ('DON', 50)
]

from collections import defaultdict
scores = defaultdict(list)
for key, val in allscores:
    scores[key].append(val)

Once you've got your scores grouped, you can just take the max of each list:

>>> topscores = dict( (k, max(v)) for k, v in scores.items() )
>>> print(topscores)
{'ABC': 300, 'DON': 90, 'JON': 205}

Upvotes: 2

Christian
Christian

Reputation: 1586

Found a solution that works:

scores_list = [
    ('ABC', 129),
    ('JON', 205),
    ('DON', 90),
    ('ABC', 300),
    ('DON', 50)
]

scores_history_dict = { k1: [v2 for (k2, v2) in scores_list if k1 == k2] for (k1, v1) in scores_list }
print scores_history_dict

highscores_dict = { k1: max([v2 for (k2, v2) in scores_list if k1 == k2]) for (k1, v1) in scores_list }
print highscores_dict

Any thoughts? Anyone with a more pythonic, smarter approach?

Upvotes: 1

Related Questions