How to print specific value from key in a dictionary?

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)

Answers


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

Need Your Help

ROS with QtCreator: autocompletion

c++ cmake qt-creator ros catkin

I'm using and like QtCreator to code and build my ROS projects written in c++.

Crashlytics is not sending Crash report from iPhone

ios crash crash-reports crashlytics

I've setup the Crashlytics in my one iOS application and installed the application on a real device. My Crashlytics Dashboard is displaying that, I've successfully added the app. However, it's not