0% found this document useful (0 votes)
2 views3 pages

Programming Assignment Unit 8

This document outlines a Python programming assignment focused on file handling, dictionaries, and exception handling. It includes a program that reads a dictionary of fruits and their colors from a file, inverts the dictionary, and writes the inverted data to another file while handling potential file errors. The assignment emphasizes the importance of error handling and data transformation in Python programming.
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)
2 views3 pages

Programming Assignment Unit 8

This document outlines a Python programming assignment focused on file handling, dictionaries, and exception handling. It includes a program that reads a dictionary of fruits and their colors from a file, inverts the dictionary, and writes the inverted data to another file while handling potential file errors. The assignment emphasizes the importance of error handling and data transformation in Python programming.
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

Topic: File Handling, Dictionaries, and Exception Handling in Python

1. Input File (Original Dictionary)


Filename: [Link]

apple:red
banana:yellow
cherry:red
mango:yellow
grapes:black,green
plum:purple
Each line represents a dictionary entry where:
The key is a fruit name
The value is one or more colors separated by commas

2. Python Program

Python
# Program to read a dictionary from a file, invert it,
# and write the inverted dictionary to another file
# with exception handling for file errors.

def read_dictionary(filename):
"""Reads key-value pairs from a file and returns a dictionary."""
data = {}
try:
with open(filename, "r") as file:
for line in file:
line = [Link]()
if ":" in line:
key, values = [Link](":")
value_list = [Link](",")
data[key] = [[Link]() for v in value_list]
except FileNotFoundError:
print("Error: Input file not found.")
except IOError:
print("Error: Unable to read the file.")
return data

def invert_dictionary(original_dict):
"""Inverts the dictionary so values become keys."""
inverted = {}
for key, values in original_dict.items():
for value in values:
if value not in inverted:
inverted[value] = []
inverted[value].append(key)
return inverted

def write_dictionary(filename, dictionary):


"""Writes a dictionary to a file."""
try:
with open(filename, "w") as file:
for key, values in [Link]():
[Link](f"{key}:{', '.join(values)}\n")
except IOError:
print("Error: Unable to write to the file.")

# Main program execution


input_file = "[Link]"
output_file = "inverted_fruits.txt"

original_dict = read_dictionary(input_file)
inverted_dict = invert_dictionary(original_dict)
write_dictionary(output_file, inverted_dict)

print("Dictionary inversion completed successfully.")

3. Output File (Inverted Dictionary)


Filename: inverted_fruits.txt

red:apple, cherry
yellow:banana, mango
black:grapes
green:grapes
purple:plum

4. Technical Explanation (200+ Words)

This program demonstrates the use of file handling, dictionaries, and exception handling in
Python, as discussed in Chapter 14 of Think Python by Downey (2015). The goal of the
program is to read dictionary data from a text file, invert the dictionary, and then write the
inverted dictionary to a new file.
The read_dictionary() function opens the input file using the with open() statement, which
ensures the file is properly closed after use. Each line of the file is stripped of whitespace and
split using the colon (:) delimiter to separate keys from values. When multiple values exist, such
as in the case of grapes having more than one color, the values are further split by commas and
stored as a list. Exception handling is implemented using try and except blocks to catch
FileNotFoundError and IOError, preventing the program from crashing if the file is missing or
unreadable.
The invert_dictionary() function reverses the mapping of the dictionary. Instead of fruits being
keys and colors being values, colors become keys and fruits become values. This is achieved
by iterating through each key-value pair and appending the original key to a list associated with
each value. This approach allows multiple fruits to share the same color without overwriting
data.
Finally, the write_dictionary() function writes the inverted dictionary to an output file. Each key
and its associated list of values are formatted into a readable line of text. Exception handling is
again used to manage potential file writing errors. Overall, this program demonstrates
persistence, data transformation, and robust error handling in Python file operations.

References (APA Style)

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.
W3Schools. (n.d.). Python file open.

You might also like