Chapter 5: Application of dictionaries

Employee database

face Josiah Wang

Dictionaries can be used in many different scenarios. These set of exercises in this chapter will hopefully help you appreciate all the different ways dictionaries can be used in your programs!

Let us try applying dictionaries to the first use case of storing the names of a list of employees by their IDs.

Let us also practise reading text files and using string methods while we are at it!

First, download employees.txt, and save it to the same directory as where you plan to write your script. You may notice that some employees’ names are made up of special characters. Thus, I recommend saving the file (by right clicking on the link, or save it using your browser), and not just copy-and-pasting the text into a text editor to avoid issues with these characters.

Your first task is to write a function load_database() that reads from a given text file and returns a dict that contains the employee ID as the key and the employee’s name as the value.

The function takes one input argument: a str that specifies the name of the file from which to read.

Assume that the text file will always be in the following format (and employee names will not contain a comma).

14835634,Slađana Ellsworth
69983058,Arianna Dragović
69448225,Delara Babič
83512249,Goda MacBeth

Here is a reminder of how you can read from a file - hopefully you will start getting comfortable doing this!

textfile = open("employees.txt")
for line in textfile:
    # Do something with line
    stripped_line = line.strip()

Sample usage

>>> employee_dict = load_database("employees.txt")
>>> print(employee_dict)
{'14835634': 'Slađana Ellsworth', '69983058': 'Arianna Dragović', '69448225': 'Delara Babič', '83512249': 'Goda MacBeth', '28836869': 'Fàtima Gulyás', '82660090': 'Meri Chaudhary', '61098940': 'Loukios Rubio', '50196408': 'Asdrúbal Van Apeldoorn', '14973705': 'Hermina Haas', '25872463': 'Rosa Burgess', '51904155': 'Kailani Bakker', '06106396': 'Monika Moray', '87491761': 'Bernarda Alexander', '37935295': 'Gwallter Choungxaim', '15304638': 'Miriam Leverenz', '84819522': 'Aurelius Tobias', '30195178': 'Lennart Debenham', '55327620': 'Meino Booth', '14817102': 'Agathe Davies', '54835190': 'Neelima Voll'}