Task: Write a program to read dictionary items from a file and then write the inverted dictionary to a file.
Problem: The new output_file is created, but it’s created blank. I’ve read a few forums and tried to make some changes (like adding a .close(), but this seems to have mixed reviews when already using with), so I’ve taken that bit out. Unsure where to go next to improve my code and get the right result! New to coding.
- tried adding .close() to the code, then removed
- tried modifying the contents of input_file, adding curly brackets, making list items strings, etc. — unsure what is correct here, does it have to be a properly formatted list?
- added if line.count section with continue
Current contents of maindictionary.txt
{
'Art': ['Pocahontas', 'Jasmine', 'Tiana'],
'Computer Science': ['Rapunzel', 'Cinderella', 'Jasmine', 'Moana'],
'English': ['Aurora', 'Rapunzel', 'Mulan', 'Tiana', 'Pocahontas'],
'Geography': ['Belle', 'Cinderella', 'Ariel', 'Thumbelina'],
'History': ['Cinderella', 'Ariel', 'Thumbelina', 'Aurora'],
'Physical Education': ['Aurora', 'Mulan', 'Belle', 'Ariel'],
'Mathematics': ['Jasmine', 'Aurora', 'Rapunzel', 'Moana'],
'Science': ['Moana', 'Tiana', 'Pocahontas', 'Thumbelina', 'Belle']
}
Current code
# indicate the file paths for the two files
input_file = "/Python/maindictionary.txt"
output_file = "/Python/inverteddictionary.txt"
# read the original dictionary from a file
def read_dictionary(input_file):
main_dictionary = {}
with open(input_file, 'r') as file:
for line in file:
if line.count(',') != 1:
continue
k, v = line.strip().split(',')
main_dictionary[k.strip()] = v.strip()
return main_dictionary
# invert the dictionary
def invert_dictionary(main_dictionary):
inverted_dictionary = {}
for key, value in main_dictionary.items():
if value not in inverted_dictionary:
inverted_dictionary[value] = [key]
else:
inverted_dictionary[value].append(key)
return inverted_dictionary
# write the inverted dictionary to a different file
def write_inverted_dictionary(inverted_dictionary, output_file):
with open(output_file, 'a') as file:
for k, v in inverted_dictionary.items():
file.write(f"{k}: {', '.join(v)}n")
# read the main dictionary from the file
main_dictionary = read_dictionary(input_file)
# invert the main dictionary, like in programming assignment 7
inverted_dictionary = invert_dictionary(main_dictionary)
# write the inverted dictionary to a new file
write_inverted_dictionary(inverted_dictionary, output_file)
Sarah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.