Hello,
Similar questions like this have been previously answered, but this question is different because it has only one part while similar questions have 2 parts and their solutions is a combination of the 2 parts. I have not been able to find an absolute solution for this part.
QUESTION:
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:(A screenshot of my learning Journal Unit 7 is attached below)
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:
Thanks for the question. Here is the completed code for this problem. Comments are included so that you understand whats going on. Let me know if you have any doubts or if you need anything to change. Thank You !! ======================================================================================== # read a file containing a dictionary and returns a dictionary def read_dictionary(filename): dictionary={} with open(filename,'r') as infile: for line in infile.readlines(): line = line.strip().split(':') key = line[0].strip('\'') values = [item.strip('\'') for item in line[1].strip('[]').split(',')] dictionary[key]=values return dictionary # 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()
=====================================================================================
Input and output files
Hello, Similar questions like this have been previously answered, but this question is different because it has only one...