how to write a Python program to read from a file, invert the dictionary, and write to a different file.
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
Comments
Leave a comment