0

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)
Mark Tolonen
  • 148,243
  • 22
  • 160
  • 229
Bruh
  • 3
  • 1
  • Does this answer your question? [Convert a String representation of a Dictionary to a dictionary?](https://stackoverflow.com/questions/988228/convert-a-string-representation-of-a-dictionary-to-a-dictionary) – Montgomery Watts Jan 01 '21 at 05:35
  • look at this example from yesterday and see if it helps -- https://stackoverflow.com/questions/65519305/how-can-i-add-multiple-dictionaries-to-a-key-inside-a-main-dictionary-example-i/65521935#65521935 – Joe Ferndz Jan 01 '21 at 05:49
  • Study python. Use python's features for OO design, i.e. use classes. `class Particle` and make `charge`, `energy` and `spin` instance attributes. In case you don't need any methods you can use named tuples or dataclasses – Pynchia Jan 01 '21 at 06:06
  • Does this answer your question? [How to get the value of a variable given its name in a string?](https://stackoverflow.com/questions/9437726/how-to-get-the-value-of-a-variable-given-its-name-in-a-string) – Georgy Jan 02 '21 at 11:29

1 Answers1

2

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)
Mark Tolonen
  • 148,243
  • 22
  • 160
  • 229