Answer to Question #199663 in Python for FORTUNE AIDOO

Question #199663

def invert_dict(d):

   inverse = dict()

   for key in d:

      val = d[key]

     if val not in inverse:

        inverse[val] = [key]

     else:

        inverse[val].append(key)

   return inverse 

Modify your program from the function above 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 input file for your original dictionary (with at least six items)
1
Expert's answer
2021-05-27T19:08:49-0400
def invert_dict(d):
   inverse = dict()
   for key in d:
      val = d[key]
      if val not in inverse:
        inverse[val] = [key]
      else:
        inverse[val].append(key)
   return inverse 


InputFile = "H:\\InputFile.txt"
OutFile   = "H:\\OutFile.txt"
infile  = open(InputFile,"r")
outfile = open(OutFile,"w")
lineRead = (infile.read()).split("\n")
infile.close()


Keys=[]
Value=[]
d = dict()
for r in range(0,len(lineRead)):
    temp = lineRead[r].split("\t")
    d[temp[0]] = temp[1]
print("\nOriginal Input Dict.: \n",d)
d = invert_dict(d)
print("\nDict. after inversion: \n",d)


for k in d:
    val = d[k]
    outfile.write("%s\t%s\n"%(k,val))
outfile.close()   


Input and Output File:











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