繁体   English   中英

创建一个字典,同时保留另一个字典中的键。 - Python

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

我希望能够使用从运行代码中获得的值创建一个新字典,但我想保留第一个字典中的值。

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

我的 output 是:18、1、40,这就是“总”变量的内容。

我希望这些数字成为我的新字典 (highScores) 中的值,同时保留旧字典 (d) 中的键。

新字典不应具有用户输入的名称。 所以如果我输入“bob”,他不应该出现在新字典中,等等。

新字典 output 应该是这样的:highScores = {'toms':18, 'sammy': 1, 'ted': 40}

谢谢!

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 是:{'bob':9,'toms':11,'sammy':1,'ted':14}

在这里,我让 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM