Answer to Question #256343 in Python for Raymond Ekwubiri

Question #256343
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: How to format each dictionary item as a text string in the input file. How to covert each input string into a dictionary item. How to format each item of your inverted dictionary as a text string in the output file. 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: The input file for your original dictionary (with at least six items). The Python program to read from a file, invert the dictionary, and write to a different file. The output file for your inverted dictionary. A description of how you chose to encode the original dictionary and the inverted dictionary in text files.
1
Expert's answer
2021-10-25T14:50:08-0400
# 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()

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS