Dictionaries

Work through the problem before opening the solution.


top_scores

We are running an online game that hosts events where players work together on teams. We have a "teams" dict where the key is a team name, and its value is a list of (user, score) tuples listing their score for the event, like this:

teams = {
  'team23': [('arun', 23), ('maya', 6), ('smith', 10), ('billy', 3)],
  ...
}

Some of the players may have a bonus number, stored in a separate "bonuses" dict like this:

bonuses = {
  'arun': 3,
  'jennifer': 2,
  'maya': 10,
  'billy': 2
}

We'll say the total-score for a player is their score from the teams dict, plus their bonus number if they have a bonus. Write the code for a top_scores() function that takes the "teams" and "bonuses" dicts and a team-name and returns a list of (name, total-score) tuples for the players on that team, but only the players with a total-score of 10 or more.

With the dicts shown above, the result for 'team23' is shown below. The bonus is added to make each total-score, and only players with total-score of 10 or more are included in the list. The list may be in any order.

# Example call with dicts as shown above
top_scores(teams, 'team23', bonuses) ->
[('arun', 26), ('maya', 16), ('smith', 10)]
def top_scores(teams, team, bonuses):
View solution
def top_scores(teams, team, bonuses):
    result = []
    pairs = teams[team]
    for pair in pairs:
        user = pair[0]  # Helpful to store in named var
        score = pair[1]
        if user in bonuses:
            score += bonuses[user]
            # Here if-bonus logic modifies score var
            # Could put if-bonus logic later
        if score >= 10:
            tuple = (user, score)
            result.append(tuple)
    return result