list - Dictionary python -
1st text file format . cake,60 cake,30 tart,50 bread,89 2nd text file format . cake,10 cake,10 tart,10 bread,10 code have tried.
from collections import defaultdict answer = defaultdict(int) recordnum = int(input("which txt files want read ")) count = 1 counter = 0 counst = 1 countesr = 0 while recordnum > counter: open('txt'+str(count)+'.txt', 'r') f: line in f: k, v = line.strip().split(',') answer[k.strip()] += int(v.strip()) count = count+1 counter = counter+1 print(answer) the problem.
i want dictionary {'cake': '110', 'tart': '60', 'bread': '99'} prints {'cake': '30', 'tart': '50', 'bread': '89'} instead of "cake" value adding other cake values txt file 1 , 2 gets replaced latest value. how solve issue. tried make if write 3, open , add 3 txt files, named, txt1.txt, txt2.txt , txt3.txt
the problem 2nd file doesnt read:
which txt files want read 2 defaultdict(<class 'int'>, {}) defaultdict(<class 'int'>, {'cake': 60}) defaultdict(<class 'int'>, {'cake': 90}) defaultdict(<class 'int'>, {'tart': 50, 'cake': 90}) defaultdict(<class 'int'>, {'tart': 50, 'bread': 89, 'cake': 90}) >> terminating you make these edits read files (note: assumes text files named txt1.txt, txt2.txt, txt3.txt , on..):
from collections import defaultdict answer = defaultdict(int) number_of_records = int(input("how many text files want read?")) in range(1, number_of_records+1): open('txt{}.txt'.format(i), 'r') file: line in file: k, v = line.strip().split(',') answer[k] += int(v) print(answer) how many text files want read? >> 2 defaultdict(<class 'int'>, {'bread': 99, 'tart': 60, 'cake': 110}) >> terminating wiki
Comments
Post a Comment