Reputation: 11
Our teacher set us a challenge to make a program that will allow users to input a symbol of an element and the program should output some info about the element.
To do this I have to use dictionaries. Currently I have this:
elements = {"Li": "Lithium" " 12" " Alkali Metal"}
element = input("Enter an elemental symbol: ")
print (elements[element])
This prints everything that is related to Li.
I was wondering how I would be able to only output, say Alkali Metal, rather than everything associated with Li? (Yes I know 12 isn't Lithium's atomic number)
Upvotes: 0
Views: 6605
Reputation: 180411
You currently have one string as a value so there is not much you can do reliably. You would need to store separate values which you could do with a sub-dict:
elements = {"Li": {"full_name":"Lithium", "num":"12", "type":"Alkali Metal"}}
Then just access the nested dict using the key of what particular value you want to get:
In [1]: elements = {"Li": {"full_name":"Lithium", "num":"12", "type":"Alkali Metal"}}
In [2]: elements["Li"]["num"]
Out[2]: '12'
In [3]: elements["Li"]["full_name"]
Out[3]: 'Lithium'
In [4]: elements["Li"]["type"]
Out[4]: 'Alkali Metal'
If you have strings with no comma separating each substring, python will create a single string:
In [5]: "Lithium" " 12" " Alkali Metal"
Out[5]: 'Lithium 12 Alkali Metal'
In [6]: "Lithium","12","Alkali Metal"
Out[6]: ('Lithium', '12', 'Alkali Metal') # now its a three element tuple
Upvotes: 6