1

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

1 Answer 1

2

Modify:

e_dict[word] = key

to:

e_dict[word] = [key]

You want to be able to append, so you should create an initial list with [key] inside - otherwise you're trying to append to a string which is why you're getting:

Attribute error: 'str' object has no attribute 'append'

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.