Search code examples
pythonlist-comprehensiondictionary-comprehension

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?


Solution

  • 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}