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

Dictionary File Processing in Python

The document describes a Python program that processes a dictionary from an input file, inverts it, and writes the result to an output file. It includes three main functions: reading the dictionary from a file, inverting the dictionary, and writing the inverted dictionary to a new file, with error handling for various exceptions. The program demonstrates file handling, dictionary manipulation, and structured data processing in Python.

Uploaded by

Joseph Njovu
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

Dictionary File Processing in Python

The document describes a Python program that processes a dictionary from an input file, inverts it, and writes the result to an output file. It includes three main functions: reading the dictionary from a file, inverting the dictionary, and writing the inverted dictionary to a new file, with error handling for various exceptions. The program demonstrates file handling, dictionary manipulation, and structured data processing in Python.

Uploaded by

Joseph Njovu
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

Dictionary File Processing in Python

1. Input File (original_dict.txt)

apple: red
banana: yellow
cherry: red
mango: yellow
grapes: black, green
orange: orange

2. Python Program
def read_dictionary_from_file(filename):
data_dict = {}

try:
with open(filename, 'r') as file:
for line in file:
line = [Link]()

if not line:
continue

key, values = [Link](':')


value_list = [[Link]() for v in [Link](',')]

data_dict[[Link]()] = value_list

except FileNotFoundError:
print("Error: Input file not found.")
except ValueError:
print("Error: File format is incorrect.")
except Exception as e:
print(f"Unexpected error: {e}")

return data_dict

def invert_dictionary(original_dict):
inverted_dict = {}

for key, values in original_dict.items():


for value in values:
if value not in inverted_dict:
inverted_dict[value] = []
inverted_dict[value].append(key)

return inverted_dict

def write_dictionary_to_file(filename, dictionary):


try:
with open(filename, 'w') as file:
for key, values in [Link]():
line = f"{key}: {', '.join(values)}\n"
[Link](line)

except Exception as e:
print(f"Error writing to file: {e}")
input_file = "original_dict.txt"
output_file = "inverted_dict.txt"

original_dict = read_dictionary_from_file(input_file)
inverted_dict = invert_dictionary(original_dict)
write_dictionary_to_file(output_file, inverted_dict)

print("Dictionary inversion completed successfully.")

3. Output File (inverted_dict.txt)

red: apple, cherry


yellow: banana, mango
black: grapes
green: grapes
orange: orange

4. Technical Explanation

This Python program demonstrates file handling, dictionary manipulation, and


exception handling. The program is divided into three main functions: reading the file,
inverting the dictionary, and writing the result to a new file.

The read_dictionary_from_file() function opens the input file in read mode


using a with statement, which ensures proper file closure after execution. Each line is
stripped of whitespace and split using the colon (:) delimiter to separate keys and
values. Since some keys may have multiple values (for example, "grapes: black,
green"), the values are further split using a comma and stored as a list. Exception
handling is implemented to manage errors such as missing files
(FileNotFoundError) and incorrect formatting (ValueError).

The invert_dictionary() function reverses the mapping of the dictionary. Instead


of keys pointing to values, values become keys pointing to lists of original keys. This
is achieved by iterating through each key-value pair and appending the key to the
corresponding value in the new dictionary. This ensures that duplicate values
correctly map to multiple keys.

The write_dictionary_to_file() function outputs the inverted dictionary into a


new file. It formats each entry as a string where values are joined by commas for
readability.

Overall, the program demonstrates persistence using files, structured data processing
with dictionaries, and robust error handling, aligning with Python file handling
concepts.

5. References

Downey, A. (2015). Think Python: How to think like a computer scientist (2nd ed.).
Green Tea Press.
Schafer, C. (2016). Python Tutorial: File Objects - Reading and Writing to Files.
YouTube.

W3Schools. (n.d.). Python File Handling.

You might also like