I am using the following code to 'invert' a dictionary. Some of the keys in the source dictionary have synonyms in other entries, so where there are multiple values for an inverted key I am trying to append eg commandante = captain and so does capitano = captain, so I am trying to achieve captain : commandante, capitano. I have used defaultdict which I naively thought would solve my problem, but I continuely get an Attribute error: 'str' object has no attribute 'append'
def form_eng_dict():
#temp_dict = pickle.load( open( "penult_dict.txt", "rb" ) )
temp_dict ={'commandante': 'captain', 'capitano':'skipper,captain', 'alaggio': 'towing, hauling'}
try:
e_dict = pickle.load( open( "penult_eng.txt", "rb" ) )
except:
e_dict = defaultdict(list)
for key, value in temp_dict.items():
for word in value.split(','):
word.strip(' ')
#print(word)
if word not in e_dict:
e_dict[word] = key
else:
e_dict[word].append(key) # causes error
for key, value in e_dict.items():
print(key, value)
pickle.dump(temp_dict, open( "penult_eng.txt", "wb" ) )
I am uncertain what I am doing incorrectly and how to solve the issue.I don't understand how I am creating a string. I am sure that I am making an absolutely basic error and will feel really stupid when you point out my error(s)! But thanks for your time