Answer to Question #203809 in Python for dwayne

Question #203809

how to write a Python program to read from a file, invert the dictionary, and write to a different file.



1
Expert's answer
2021-06-06T08:55:50-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"
infile  = open(InputFile,"r")
lineRead = (infile.read()).split("\n")
infile.close()




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


Out   = "H:\\OutFile.txt"
outfile = open(Out,"w")
for k in d:
    val = d[k]
    outfile.write("%s\t%s\n"%(k,val))
outfile.close()    







Contents of H:\\InputFile.txt

Key1 Value1

Key2 Value2

Key3 Value3

Key4 Value4

Key5 Value5

Key6 Value6


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