Modify your program from Learning Journal Unit 7 to read dictionary items from a file and write the inverted dictionary to a file. You will need to decide on the following:
Create an input file with your original three-or-more items and add at least three new items, for a total of at least six items.
Include the following in your Learning Journal submission:
# inverts the dictionary and returns the reversed dictionary
def invert_dict(d):
inverse={}
for key, items in d.items():
for item in items:
inverse[item]=key
return inverse
# takes in a dictionary and the filename and writes the dictionary to that file
def write_to_file(inverted_dictionary,filename):
with open(filename,'w') as outfile:
for key,value in inverted_dictionary.items():
outfile.write('\'{0}\':[\'{1}\']\n'.format(key,value))
print('{} updated successfully.'.format(filename))
def main():
infile_name = 'dictionary.txt' # file that needs to be read from
d = read_dictionary(infile_name) # reads the file which returns a dictionary
reversed_d = invert_dict(d) # reverses the dictionary and return the reversed dictionary
print(reversed_d) # you can comment this line
outfile_name='inverted_dict.txt' # file that needs to be updated with the reversed dictionary
write_to_file(reversed_d,outfile_name) # writes dictionary to the file
main()
Comments
Leave a comment