imox
imox

Reputation: 1554

'str' object does not support item assignment error in python

The following code:

words={}
words_with_meaning_list=[]
words_without_meaning_list=[]
words_file=open('words/word_meaning.txt','a+')
words_with_meaning_file=open('words/words_with_meaning.txt','a+')
words_without_meaning_file=open('words/words_without_meaning.txt','a+')

words_with_meaning_list=words_with_meaning_file.readlines()
words_without_meaning_list=words_without_meaning_file.readlines()
words=words_file.read()

def add_word(word,meaning='none'):
    words[word]=meaning
    if(meaning=='none'):
        words_without_meaning_list.append(word)
    else:
        words_with_meaning_list.append(word)    

def input_machine(repeat):
    if(repeat=='y' or repeat=='Y'):
        the_word=input('Enter the word you want to add:')
        choice=input('If you know the meaning of the word press y or Y:')

        if(choice=='y' or choice=='Y'):
            the_meaning=input('Enter the meaning:')
            add_word(the_word,the_meaning)
        else:       
            add_word(the_word)
    else:
        s1='\n'.join(words_with_meaning_list)
        s2='\n'.join(words_without_meaning_list)
        s3='\n'.join(words)
        print (s1)
        print (s2)
        print (s3)
        words_with_meaning_file.write(s1)
        words_without_meaning_file.write(s2)
        words_file.write(s3)    

input_machine('y')

repeat=input('Do you want to continue adding meaning. press y or Y:')

while(repeat=='y'):
    input_machine(repeat)
    repeat=input('Do you want to continue adding meaning. press y or Y:')


print (words)   

gives the following error TypeError: 'str' object does not support item assignment.

The error is in ' words[word]=meaning '. I can't understand this error. words is dictionary type and we can add new key and value in the above format then why am i getting the error. Please help me.

Upvotes: 1

Views: 2017

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117886

You are changing the variable words. You start with

words={}

Then a few lines later

words=words_file.read()

After the second line, words is now a str, so you cannot do

words[word]=meaning

Upvotes: 3

Related Questions