[go: up one dir, main page]

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

Week8

The document outlines a programming assignment that involves creating an input file containing fruit-color pairs, writing a Python program to read this file, invert the dictionary, and write the inverted dictionary to an output file. It includes detailed explanations of the functions used for reading, inverting, and writing the dictionary, as well as exception handling for file operations. The expected output format for the inverted dictionary is also provided.

Uploaded by

falakfraidoon
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)
11 views4 pages

Week8

The document outlines a programming assignment that involves creating an input file containing fruit-color pairs, writing a Python program to read this file, invert the dictionary, and write the inverted dictionary to an output file. It includes detailed explanations of the functions used for reading, inverting, and writing the dictionary, as well as exception handling for file operations. The expected output format for the inverted dictionary is also provided.

Uploaded by

falakfraidoon
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
You are on page 1/ 4

Programming Assignment Unit 8

Step 1: Creating the Input File


Let's name the input file input_dict.txt with the following content:
apple: red
banana: yellow
cherry: red
mango: yellow
grapes: black, green

Step 2: Writing the Python Program


Here's the Python program that reads from the file, inverts the dictionary, and writes the inverted
dictionary to another file:

# Python Program to Read, Invert, and Write Dictionary

def read_dictionary(file_path):
"""Reads a dictionary from a file."""
dictionary = {}
try:
with open(file_path, 'r') as file:
for line in file:
key, value = line.strip().split(': ')
values = [v.strip() for v in value.split(',')]
dictionary[key] = values
except FileNotFoundError:
print(f"Error: The file {file_path} does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
return dictionary

def invert_dictionary(original_dict):
"""Inverts a dictionary."""
inverted_dict = {}
for key, values in original_dict.items():
for value in values:
if value in inverted_dict:
inverted_dict[value].append(key)
else:
inverted_dict[value] = [key]
return inverted_dict

def write_dictionary(file_path, dictionary):


"""Writes a dictionary to a file."""
try:
with open(file_path, 'w') as file:
for key, values in dictionary.items():
file.write(f"{key}: {', '.join(values)}\n")
except Exception as e:
print(f"An error occurred while writing to the file: {e}")

def main():
input_file = 'input_dict.txt'
output_file = 'inverted_dict.txt'

# Read the original dictionary from the input file


original_dict = read_dictionary(input_file)

# Invert the dictionary


inverted_dict = invert_dictionary(original_dict)

# Write the inverted dictionary to the output file


write_dictionary(output_file, inverted_dict)
print("Inverted dictionary has been written to", output_file)

if __name__ == "__main__":
main()

Step 3: Creating the Output File


After running the program, the output file inverted_dict.txt should look like this:
red: apple, cherry
yellow: banana, mango
black: grapes
green: grapes
Technical Explanation:
The Python program reads a dictionary from a file, inverts the dictionary, and writes the inverted
dictionary to another file. Below is a detailed explanation of each part of the program:
1. Reading the Dictionary: The function read_dictionary reads key-value pairs from the
input file. It handles multiple values for a single key by splitting values on commas and
stripping any extraneous whitespace. Exception handling ensures that if the file doesn't
exist or another error occurs, a relevant error message is printed.
2. Inverting the Dictionary: The invert_dictionary function takes the original dictionary
and inverts it. For each key in the original dictionary, it iterates over its associated values,
adding the key to the list of values in the inverted dictionary. If a value already exists as a
key in the inverted dictionary, the original key is appended to the existing list; otherwise,
a new list is created.
3. Writing the Inverted Dictionary: The write_dictionary function writes the inverted
dictionary to an output file. It formats each key-value pair as key: value1, value2 and
handles exceptions that may occur during file writing.
4. Main Function: The main function orchestrates the process by specifying the input and
output file paths, calling the functions to read, invert, and write the dictionary, and
providing feedback on successful completion.
5. Exception Handling: The program includes exception handling to deal with common
file-related errors, ensuring robustness and user-friendly error messages.
This program demonstrates practical use of file handling and dictionary manipulation in Python,
reinforcing concepts such as reading from and writing to files, dictionary operations, and error
handling.

References:
Downey, A. (2015). Think Python: How to think like a computer scientist. Green Tree Press.
Python Software Foundation. (2021). Python Language Reference, version 3.9. Available at
Python.org.
https://www.python.org

You might also like