Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

How to add values of keys in dictionaries from input in python

I'm very new to python and am trying to figure out a way to access dictionaries from an input and then add values of similar keys in the dictionaries, then print the resulting value from adding those similar key values. The bad code I have now is:

p = {  
    "charge" : 1,  
    "energy": 938,  
    "spin": 1/2,  
}  
n = {  
    "charge" : 0,  
    "energy": 940,  
    "spin": 1/2,  
}  
e = {  
    "charge": -1,  
    "energy": 0.511,  
    "spin": 1/2,  
}  
x = input("First particle:")  
y = input("Second particle:")  
tcharge = x.get("charge")+y.get("charge")  
tenergy = x.get("energy")+y.get("energy")  
tspin = x.get("spin")+y.get("spin")  
print(tcharge)  
print(tenergy)  
print(tspin)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use a dictionary to store the names of the particles and their descriptions. Your inputs are strings so the keys of the dictionary should be strings. The values in the dictionary are the dictionaries you've created:

particle = {}
particle['p'] = {  
    "charge" : 1,  
    "energy": 938,  
    "spin": 1/2,  
}  
particle['n'] = {  
    "charge" : 0,  
    "energy": 940,  
    "spin": 1/2,  
}  
particle['e'] = {  
    "charge": -1,  
    "energy": 0.511,  
    "spin": 1/2,  
}  
x = input("First particle:")  
y = input("Second particle:")  
tcharge = particle[x]['charge'] + particle[y]['charge']
tenergy = particle[x]['energy'] + particle[y]['energy']
tspin = particle[x]['spin'] + particle[y]['spin']
print(tcharge)  
print(tenergy)  
print(tspin)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...