Home > Software engineering >  'str' object has no attribute 'append' attribute error when i try append to dict
'str' object has no attribute 'append' attribute error when i try append to dict

Time:12-10

I'm a beginner programmer and this is my first post on this website. I trying to append value to the existing key in the dictionary, but I keep getting attribute errors. I already tried append value to the existing key on another project and it worked perfectly. So I'm pretty much at a dead end. I would really appreciate it if you guys can point out my mistake and help me to fix my code.

import glob
import os

def main():

 direct = r"C:\Users\Inzaghi\Desktop\Ondra_origin"

 main_dict={}

 for filename in glob.glob(os.path.join(direct, '*.spe')): 
  
    with open(filename,'r') as file:    
        print ('file read: '   filename)
        lst=[]
        for line in file:
            line = line.replace('# ','')
            if len(line) == 14:
                line = line.rstrip().split()
                lst.append(line[1])
      
        for count, n in enumerate(lst[:-4]):
            if count in main_dict:
                main_dict[count].append(n)
            else:
                 main_dict[count]=n
                 
with open (direct '\celkovy_file.txt','a') as f:
     for i in range(0,len(main_dict)):
         f.write(main_dict[i]   '\n')
print('Done')

if __name__=='__main__':
    main() 

CodePudding user response:

main_dict[count]  = n

Should give you the desired result

Though that will make the values into a long string. If you want the values to be a list you could do:

       if count in main_dict:
            main_dict[count].append(n)
        else:
             main_dict[count]= [n]

CodePudding user response:

Change this

for count, n in enumerate(lst[:-4]):
    if count in main_dict:
        main_dict[count].append(n)
    else:
        main_dict[count]=n

to

for count, n in enumerate(lst[:-4]):
    main_dict.setdefault(count, []).append(n)

dict.setdefault method will set a default value to a key (in this case an empty list) if it isn't already in the dictionary. If it exists, the append method appends the iterating item to its corresponding value list.

  • Related