[英]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.我的 output 是:18、1、40,这就是“总”变量的内容。
I would like these numbers to be the values in my new dictionary (highScores), while keeping the keys from the old dictionary (d).我希望这些数字成为我的新字典 (highScores) 中的值,同时保留旧字典 (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.
所以如果我输入“bob”,他不应该出现在新字典中,等等。
The new dictionary output should be something like: highScores = {'toms':18, 'sammy': 1, 'ted': 40}新字典 output 应该是这样的:highScores = {'toms':18, 'sammy': 1, 'ted': 40}
Thanks!谢谢!
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} Output 是:{'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.在这里,我让 highScores 使用 d 中的所有名称或“键”,并将 arrays 相加,使用 d.keys() 或 d.values() 来解析 dicts。
for key in d.keys():
if key != whatName:
high_scores[key] = sum(d[key])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.