# 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()
Comments
Leave a comment