Week8
Week8
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 main():
input_file = 'input_dict.txt'
output_file = 'inverted_dict.txt'
if __name__ == "__main__":
main()
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