Dictionaries#
The final basic data structure that we will be covering in this course is the dictionary (of type dict
). This collection is referred to as a “dictionary” because it consists of key-value pairs. In the case of a literal dictionary, there are a set of words which act as the “keys” and a set of definitions which act as the “values”. In a programming context, it doesn’t have to be words and definitions, but the same principle applies. Let’s consider a simple example:
group_2 = {'Be' : 4,
'Mg' : 12,
'Ca' : 20,
'Sr' : 38,
'Ba' : 56}
type(group_2)
dict
In this example, we have created a dictionary in which the keys are the symbols of the group \(2\) elements, and the values are their corresponding atomic numbers. The general syntax for creating a dictionary is a comma-separated collection of key : value pairs enclosed by curly brackets:
name_of_dictionary = {key_1 : value_1, key_2 : value_2, key_3 : value_3}
Once a dictionary has been created, its keys can be used just to retrieve its values, much like an index in a list:
group_2['Ca']
20
Note that whilst this process is similar to indexing a list, dictionaries cannot be indexed (with an int
) like a list:
group_2[2]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[3], line 1
----> 1 group_2[2]
KeyError: 2
Error
Aha, a new error type! This is a KeyError, which indicates that the key we are trying to use does not exist in the dictionary. Sure enough, the keys here are all strings of group \(2\) elements, so 2
is not a valid key.
Unlike tuples, dictionaries are mutable, so we can add new key : value pairs:
group_2['Ra'] = 88
print(group_2)
{'Be': 4, 'Mg': 12, 'Ca': 20, 'Sr': 38, 'Ba': 56, 'Ra': 88}
We can also modify values that are already in the dictionary. For example, imagine that we wanted to replace the atomic number for Be with its atomic mass:
group_2['Be'] = 9.0122
print(group_2)
{'Be': 9.0122, 'Mg': 12, 'Ca': 20, 'Sr': 38, 'Ba': 56, 'Ra': 88}
Above we have replaced the atomic number, but there is also nothing stopping us from setting the value for the key 'Be'
to a tuple or list of both the atomic number and the atomic mass:
group_2['Be'] = (4, 9.0122)
print(group_2)
{'Be': (4, 9.0122), 'Mg': 12, 'Ca': 20, 'Sr': 38, 'Ba': 56, 'Ra': 88}
Exercise#
Create a dictionary describing some of the basic physical properties of silicon. For example, you could have keys like 'Symbol'
, 'Atomic Number'
, 'Atomic Mass'
, 'Melting Point'
, 'Electronegativity'
etc, with appropriate values set for each one. Test your dictionary once you have assigned it to a variable by trying to access and print different values with the appropriate keys.