Dictionaries
The final basic data structure that we will be covering in this course is the dictionary (of type dict). Dictionaries contain an ordered list of key-value pairs - much like in a real dictionary where we have words and definitions.
Dictionary basics
To see how dictionaries work, look at the following example which contains the symbols and atomic numbers of the group two elements
group_2 = {
'Be': 4,
'Mg': 12,
'Ca': 20,
'Sr': 38,
'Ba': 56
}
type(group_2)
print(group_2)dict
{'Be': 4, 'Mg': 12, 'Ca': 20, 'Sr': 38, 'Ba': 56}
Dictionary indexing
Once a dictionary has been created, each key can be used to retrieve the corresponding value, similarly to the use of an index with a list. We use square brackets [] immediately after the dictionary name and, for example, obtain the atomic number of calcium with
group_2['Ca']20
Modifying dictionaries
Dictionaries are mutable - we can add new key-value pairs as follows
group_2 = {
'Be': 4,
'Mg': 12,
'Ca': 20,
'Sr': 38,
'Ba': 56
}
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}
or perhaps we could change the value for Be to a tuple containing both the atomic number and 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}
of course, we should probably go through and change all of the entries to follow this pattern - otherwise the dictionary is a bit of a mess of information!
Exercise
Use your knowledge of dictionaries to solve the following problem
Create a dictionary containing the basic physical properties of silicon, by editing the following code so that it executes properly.
silicon_properties = {}
print(f'Silicon\'s atomic mass is {silicon_properties['amass']:.2f} u')
print(f'Silicon\'s atomic symbol is {}')
print(f'Silicon\'s electronegativity is {:.2f}')Use python to add a new entry to your dictionary containing the melting point of silicon in Kelvin - print this number as a float with two decimal places.
Don’t just edit the print commands to contain the data, make a dict and index it!