gdm
gdm

Reputation: 71

Create a dictionary while keeoping the keys from another dictionary. - Python

I would like to be able to make a new dictionary with the values I get from running my code, but I want to keep the values from the first dictionary.

import math
d = {'bob':[5,0,0,1,3], 'toms':[3,0,5,3,0], 'sammy': [0,0,0,1,0], 'ted':[5,0,0,6,3]}
highScores = {}

total = 0
v =0
whatName = str(input("what name do you want?   "))
for i in d:
    a = d[whatName] #gives us whatNames values
    b = d[i]
    if i == whatName: #skips what name is
        pass
    else:
        for k in range(len(b)):
            #print(k, end = ' ')
            value = a[k]*b[k]
        
            total= value + total
            
        print(total) 
        total = 0

my output is: 18, 1, 40 and this is what goes into the "total" variable.

I would like these numbers to be the values in my new dictionary (highScores), while keeping the keys from the old dictionary (d).

The new dictionary should not have the name that is input from the user. So if I put in "bob", he should not be appearing in the new dictionary, and so on.

The new dictionary output should be something like: highScores = {'toms':18, 'sammy': 1, 'ted': 40}

Thanks!

Upvotes: 1

Views: 1563

Answers (2)

will-hedges
will-hedges

Reputation: 1284

for key in d.keys():
    if key != whatName:
        high_scores[key] = sum(d[key])

Upvotes: 0

jasonmzx
jasonmzx

Reputation: 517

d = {'bob':[5,0,0,1,3], 'toms':[3,0,5,3,0], 'sammy': [0,0,0,1,0], 'ted':[5,0,0,6,3]}
highScores = {}

for x in d.keys():
    highScores[x] = sum(d[x])

print(highScores)

Output was: {'bob': 9, 'toms': 11, 'sammy': 1, 'ted': 14}

Here I made highScores use all the names or "keys" in d, and added up the arrays, use d.keys() or d.values() to parse thru dicts.

Upvotes: 1

Related Questions