Dictionaries#

Previously, collections of information known as list and tuple were introduced. Python has a final collection type that we will discuss here, the dictionary dict. This collection type consists of keys and values. These keys and values are analogous to the words and definitions of a traditional dictionary. Consider if we rewrite the chlorine variable as a dictionary.

chlorine = {'chemical symbol': 'Cl', 'atomic number': 17, 'average mass number': 35.45, 'x-ray scattering length': 2.76+0.05j}
print(chlorine)
{'chemical symbol': 'Cl', 'atomic number': 17, 'average mass number': 35.45, 'x-ray scattering length': (2.76+0.05j)}

Here, we are able to use the keys of the dictionaries as labels for each datum.

print(chlorine.keys())
dict_keys(['chemical symbol', 'atomic number', 'average mass number', 'x-ray scattering length'])

It is possible to access a single one of the elements of a dictionary, by passing the relevant key in lieu of an index.

chlorine['atomic number']
17

However, traditional indexing does not work for dictionaries, as the index is not a key.

chlorine[1]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[5], line 1
----> 1 chlorine[1]

KeyError: 1

We can add elements to a dictionary rather simply.

chlorine['number of isotopes'] = 2
print(chlorine)
{'chemical symbol': 'Cl', 'atomic number': 17, 'average mass number': 35.45, 'x-ray scattering length': (2.76+0.05j), 'number of isotopes': 2}

Finally, the items in a dictionary need not be single variables, like a float or an int. They can also other collections like a list or tuple.

chlorine['mass numbers'] = (35, 37)
print(chlorine)
{'chemical symbol': 'Cl', 'atomic number': 17, 'average mass number': 35.45, 'x-ray scattering length': (2.76+0.05j), 'number of isotopes': 2, 'mass numbers': (35, 37)}

Exercise#

Create a dictionary where the keys are the names of the first-row of transition metals, and the values are int of the number of valence electrons. Test your dictionary by printing some of the values.