1

I am trying to add multiple value to a single key(if found) from a file in python. I tried below code but getting this error: AttributeError: 'str' object has no attribute 'append'

file=open("Allwords",'r')
list=sorted(list(set([words.strip() for words in file])))
def sequence(word):
    return "".join(sorted(word))
dict= {}
for word in list:
    if sequence(word) in dict:
        dict[sequence(word)].append(word)
    else:
        dict[sequence(word)]=word

Thanks in advance for your help!

Abhishek Bhagate
  • 5,583
  • 3
  • 15
  • 32
  • Does this answer your question? [list to dictionary conversion with multiple values per key?](https://stackoverflow.com/questions/5378231/list-to-dictionary-conversion-with-multiple-values-per-key) or [append multiple values for one key in a dictionary](https://stackoverflow.com/q/3199171/4518341) – wjandrea Jun 24 '20 at 23:14

1 Answers1

1

You should insert the first element by putting it into a list, so that you can append subsequent items to it later on. You can do it as follows -

file=open("Allwords",'r')
list=sorted(list(set([words.strip() for words in file])))
def sequence(word):
    return "".join(sorted(word))
dict= {}
for word in list:
    if sequence(word) in dict:
        dict[sequence(word)].append(word)
    else:
        new_lst = [word]       # Inserting the first element as a list, so we can later append to it
        dict[sequence(word)]=new_lst

Now you will be able to append to it properly. In your case, the value you were inserting was just a string to which you wouldn't have been able to append. But this will work, since you are inserting a list at start to which you would be able to append to .

Hope this helps !

Abhishek Bhagate
  • 5,583
  • 3
  • 15
  • 32