Exercise 2

This exercise will walk you through the creation of a dictionary.

  1. First, load the data in the names.txt file. This file contains common names of some species. Load this into a list.
  2. Do the same thing with the species.txt file. This file contains chemical formulae for some species.
  3. Now create a dictionary where the data from names.txt are the values and the data from species.txt are the keys.
    • You should automate the creation of the dictionary by using a for loop
    • The for loop should iterate over the representation created by the zip function. You can refer to the example around line 32 in Lecture 4 for guidance.
    • HINT: Initialize the dictionary by with my_new_dict = {} just before executing the for loop.
  4. Access a value from the dictonary and print it to the screen.

Note: The same dictionary can be created by executing the following one-liner: species_dict_2 = dict(zip(species, names)).


In [27]:
with open('names.txt') as fnames:
    names = fnames.read()
    names = names.split('\n')
    print(names)
    names = filter(None, names)
print(list(names))


['Hydrogen', 'Oxygen', 'Hydroxyl', 'Water', 'Hydrogen Peroxide', '']
['Hydrogen', 'Oxygen', 'Hydroxyl', 'Water', 'Hydrogen Peroxide']