CS 1101 Programming Assignment Unit 8
CS 1101 Programming Assignment Unit 8
First, I need to create the input file input_dict.txt with the dictionary items.
Creating input_dict.txt:
apple: red
banana: yellow
cherry: red
mango: yellow
Next, I write a Python script named invert_dict.py to read the dictionary from input_dict.txt,
I open command prompt, navigate to the directory where invert_dict.py is saved, and run the
This script reads the dictionary from input_dict.txt, inverts it, and writes the inverted dictionary
to output_dict.txt.
I open the output_dict.txt file in a text editor to verify its contents. The file contain the following
inverted dictionary:
Here’s my technical explanation for the code and its output:
The provided Python script performs the task of reading a dictionary from a file, inverting it, and
writing the inverted dictionary to another file. Here’s a breakdown of how the script works:
The read_dict function opens input_dict.txt and reads its contents line by line. Each line is split
Values are further split by ', ' to handle cases where multiple values exist for a single key, and are
The invert_dict function takes the original dictionary and creates an inverted dictionary.
It iterates through each key-value pair of the original dictionary. For each value in the value list,
it adds the key to the list of keys associated with that value in the inverted dictionary.
This results in each unique value in the original dictionary mapping to a list of keys that had that
value.
It iterates over the inverted dictionary and writes each key along with its associated list of values
The script first creates the input file with the sample dictionary content (if not already created
manually).
It then reads the dictionary from the input file, inverts it, and writes the inverted dictionary to the
output file.
Input (input_dict.txt):
Output (output_dict.txt):
The inverted dictionary correctly maps each color to the corresponding fruits, demonstrating the
Downey, A. (2015). Think Python: How to think like a computer scientist (2nd ed.). Green Tea
Press.
Schafer, C. (2016, April 29). Python tutorial: file objects - Reading and writing to files [Video].
YouTube. https://youtu.be/Uh2ebFW8OYM
https://www.w3schools.com/python/python_file_handling.asp