0% found this document useful (0 votes)
20 views4 pages

Programming Assignment - Unit 8

The document describes a Python program that reads a dictionary of fruits and their colors from an input file, inverts the dictionary so that colors become keys and fruits become values, and writes the result to an output file. It includes error handling for file operations and demonstrates good file-handling practices. The program is useful for data analysis where key-value relationships need to be reversed.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views4 pages

Programming Assignment - Unit 8

The document describes a Python program that reads a dictionary of fruits and their colors from an input file, inverts the dictionary so that colors become keys and fruits become values, and writes the result to an output file. It includes error handling for file operations and demonstrates good file-handling practices. The program is useful for data analysis where key-value relationships need to be reversed.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Programming Assignment – Unit 8

Name: Camila Rocha Jauregui

Course: CS 1101 - Programming Fundamentals

Date: August 13th, 2025

1. Input File

apple: red

banana: yellow

cherry: red

mango: yellow

grapes: black

pear: green

Screenshot:

2. Python Program

# Program to read a dictionary from a file, invert it, and write it to another file

try:

# Open input file in read mode

with open('input_dict.txt', 'r') as f:

original_dict = {}

for line in f:

line = [Link]() # remove spaces and newline characters

if line: # skip empty lines


key, value = [Link](':') # separate key and value

original_dict[[Link]()] = [Link]() # store in dictionary

# Create an inverted dictionary

inverted_dict = {}

for key, value in original_dict.items():

if value not in inverted_dict:

inverted_dict[value] = [key]

else:

inverted_dict[value].append(key)

# Write inverted dictionary to output file

with open('output_inverted_dict.txt', 'w') as f:

for value, keys in inverted_dict.items():

[Link](f"{value}: {', '.join(keys)}\n")

print("Original dictionary:", original_dict)

print("Inverted dictionary:", inverted_dict)

except FileNotFoundError:

print("Error: The input file does not exist.")

except Exception as e:

print("An error occurred:", e)


Screenshot:

3. Output File

red: apple, cherry

yellow: banana, mango

black: grapes

green: pear

Screenshot:

4. Explanation

This program reads a dictionary stored in a text file and produces an inverted dictionary in a

separate output file. First, it opens the input file input_dict.txt using a with statement, ensuring

the file is automatically closed after reading. Each line is processed with strip() to remove

whitespace and newline characters. The line is then split into a key and a value using split(':').

This constructs the original_dict where fruit names are keys and their colors are values.

Next, the program creates the inverted dictionary inverted_dict. Each key-value pair from the

original dictionary is reversed: the value becomes the new key, and the original key is added to a

list of values. This approach allows multiple original keys to be grouped under the same new key

—for example, both apple and cherry share the value red.

Finally, the inverted dictionary is written to output_inverted_dict.txt. The program uses join to

convert the list of keys into a comma-separated string. Exception handling is implemented using
try-except blocks to catch common errors, such as missing input files or unexpected issues

during file processing, providing informative messages to the user.

The output demonstrates the inverted relationship: colors now act as keys, and fruits as grouped

values. This technique is useful in data analysis or applications where key-value relationships

need to be reversed. The program illustrates good file-handling practices and robust error

management, following best practices outlined by Downey (2015) and Schafer (2016).

References

● 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. [Link]

● Python File Open. (n.d.). W3Schools.

[Link]

You might also like