Session 10: More lists and dictionaries#

Introduction#

Previously you learned about lists and their splicing. In this session we will explore lists in more detail. We will also look at a new type of structure - dictionaries and how that is different from lists. We will also use what we have learned about indexing and number types - integers and floating point numbers.

Task 1 (Recap)#

  1. Have a look at the code below - try to anticipate what each line might do when executed.

  2. Then, in a terminal window, navigate to your PHAR2062 folder.

  3. Create (if it doesn’t already exist) a subfolder called Workshop_6, and then change directory into it.

  4. Start a Jupyter Notebook session, and create a fresh, empty, notebook.

  5. Copy the following code into the first cell in your new notebook, and then run it (press the ‘run’ button or hit Shift+ Enter).

    elements = ['Carbon', 'Hydrogen', 'Nitrogen', 'Oxygen']
    print(elements)
    print(elements[0])
    print(len(elements))
    elements.append('Helium')
    print(elements)
 
    weights = [12.011, 1.0078, 14.007, 15.999]
    print(weights)
    print(weights[0])
    print(len(weights))
 weights.append(4.0026)
    print(weights)

Analysis#

None of this should be too surprising, as is just a recap from what you have seen previously. Perhaps new is the idea that list elements can also be floating point numbers and integers. In fact, in Python list elements can be any type of object - including lists!

Task 2#

Again, before pasting and running the code in a new cell, please carefully read and try to guess what each line will do.

elements = [['Carbon', 12.011], ['Hydrogen', 1.0078], ['Nitrogen', 14.007], ['Oxygen', 15.999]]
print(elements)
elements.append(['Helium', 4.0026])
print(elements)
print(elements[1])
print(elements[1][0])
print(elements[1][0][3])

Analysis#

In this task, we move on to working with lists of lists, which introduces a more complex data structure where each element in the main list is itself a list. Let’s break down the code and what it does:

  1. elements = [['Carbon', 12.011], ['Hydrogen', 1.0078], ['Nitrogen', 14.007], ['Oxygen', 15.999]]

  • This creates a list of lists, where each inner list contains two items: the name of a chemical element (a string) and its atomic weight (a floating point number). The structure allows for pairing related data together within the same list.

  1. print(elements[1])

  • This accesses the second item in the elements list (remember that Python uses zero-based indexing).

  1. print(elements[1][0])

  • This is the first time we see that there can be two indices specifying first which list element in the top level list we want, and then, as that element is a list itself, the second index specifies the item in the inner list.

  • This accesses the first item ([0]) within the second list ([1]). Since ['Hydrogen', 1.0078] is the second list, this returns 'Hydrogen'.

  1. print(elements[1][0][3])

  • This line drills down one more level: it accesses the fourth character (index [3], since Python counts from zero) in the string 'Hydrogen', which is 'r'.

Task 3#

Given this list of lists elements = [['Carbon', 12.011], ['Hydrogen', 1.0078], ['Nitrogen', 14.007], ['Oxygen', 15.999]] write a short program that will print the total atomic weight of these elements. You might need to refresh how for iteration can be used to operate on all elements of a list in turn.

In case this proves challenging, one possible approach is given below - but try by yourself for 10-15 minutes before taking a peek!

Click here if you get stuck!
total_atomic_weight = 0.0
for element in elements:
    total_atom_weight = total_atomic_weight + element[1]

print('Total atomic weight = ', total_atomic_weight)

Introduction to Dictionaries#

In the previous tasks, we have been working with lists to store collections of elements and their atomic weights. While lists are useful, they can become cumbersome when we need to associate data pairs, like element names and their atomic weights. This is where dictionaries come into play.

A dictionary in Python is a collection of key-value pairs where each unique key maps to a value. Dictionaries are created using curly braces {} and use colons : to separate keys from values.

Task 4#

  1. Before running the code, try to predict what each line will do.

  2. Open your Jupyter Notebook from the previous tasks.

  3. In a new cell, copy and run the following code:

element_dict = {'Carbon': 12.011, 'Hydrogen': 1.0078, 'Nitrogen': 14.007, 'Oxygen': 15.999}
print(element_dict)
print(element_dict['Carbon'])
print(len(element_dict))
element_dict['Helium'] = 4.0026
print(element_dict)

element_dict = {'Carbon': 12.011, 'Hydrogen': 1.0078, 'Nitrogen': 14.007, 'Carbon': 15.999}
print(element_dict['Carbon'])

Analysis#

In this task, we introduce dictionaries to store element names as keys and their atomic weights as values.

  1. element_dict = {'Carbon': 12.011, 'Hydrogen': 1.0078, 'Nitrogen': 14.007, 'Oxygen': 15.999}

    • Creates a dictionary called element_dict with element names as keys and their atomic weights as values.

  2. print(element_dict['Carbon']) - Accesses the value associated with the key 'Carbon', which is 12.011.

  3. element_dict['Helium'] = 4.0026

    • Adds a new key-value pair to the dictionary with 'Helium' as the key and 4.0026 as the value.

From these examples hopefully it is apparent that dictionaries are different from lists in the way we access the elements. We can easily retrieve the values using the keys, which is often much more convenient than just indices, as in lists. It is important to remember that as keys are used to retrieve elements, they must be unique.

  1. element_dict = {'Carbon': 12.011, 'Hydrogen': 1.0078, 'Nitrogen': 14.007, 'Carbon': 15.999} print(element_dict['Carbon'])

    • As you might see, no errors are generated when defining an element_dict with two identical keys. However, afterwards there is no way of accessing the first value, therefore you should always make sure that keys are unique in the dicionary.

Task 5#

Now, let’s learn how to iterate over the dictionary.

  1. Predict what each line will do before running the code.

  2. In a new cell, copy and run the following code:

for element in element_dict:
 print(element)
  1. Modify the code to also print the atomic weights:

for element in element_dict:
    print(element, element_dict[element])

How is the output different here?

Analysis#

When you iterate over a list, you get the items in the list, one by one. But when you iterate over a dictionary, you get the keys, one by one. Forgetting about this is a common error to make!

The order in which you get the keys is the order in which they were added to the dictionary when it was created.

Task 6#

Suppose we want to calculate the molecular weight of a molecule using our element_dict.

  1. Create a dictionary called molecule to represent water (H₂O):

    molecule = {'Hydrogen': 2, 'Oxygen': 1}
  1. Write code to calculate and print the molecular weight of water using element_dict and molecule. The expected output is 18.0154

  2. Spend some time tackling this task, as it will be good practice for your miniproject task. If you are struggling, one approach can be found in water_weight.py

Conclusion#

In this session we have remined ourselves what lists do and looked at more sophisticated list applications, including lists containing lists.

We’ve also explored how dictionaries can be used to store and manipulate data pairs efficiently. By using dictionaries, we can:

  • Map element names to their atomic weights.

  • Iterate over dictionaries to perform calculations.

Dictionaries provide a powerful tool for handling structured data, especially when dealing with associations like element names and their properties in chemistry.