Noah Trotman
Noah Trotman

Reputation: 155

Counting the sum of dictionary keys

Score updates consumes a dictionary (see Example) and produces another dict with the value of the string, corresponding to the value of the letters from the dict Scoring. The output looks like Final(see below). This is what I have so far and I'm unsure on how I'm supposed to loop through the string to calculate the sum of it.

Hope you are able to help. Thank you

Example = {'Dallas':"WWLT", 'Seattle':"LLTWWT"}
Final = {'Dallas':5, 'Seattle':6}

def score_updates(weekly_result):
    Scoring = { 'W': 2, 'T': 1, 'L': 0}    
    d = {}
    total = 0
    teams = weekly_result.keys()
    for t in weekly_result:
        total += Scoring[t]
    return d[teams].append(total)

Upvotes: 4

Views: 234

Answers (2)

miradulo
miradulo

Reputation: 29710

Assuming you already had a dict Scoring, you could just use a dict comprehension with sum.

def score_updates(d):
    return {k: sum(map(Scoring.__getitem__, v)) for k, v in d.items()}

Upvotes: 3

tdelaney
tdelaney

Reputation: 77357

You need to enumerate the values along with the keys. Then you can just map each character in the value to its number and sum that

def score_updates(weekly_result):
    Scoring = { 'W': 2, 'T': 1, 'L': 0}    
    d = {}
    for team, outcomes in weekly_result.items():
        d[team] = sum(Scoring[outcome] for outcome in outcomes)
    return d

Example = {'Dallas':"WWLT", 'Seattle':"LLTWWT"}
Final = {'Dallas':5, 'Seattle':6}

test = score_updates(Example)
print("Worked?", test == Final)

Upvotes: 0

Related Questions