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:
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:
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:
Comments
Leave a comment