user7214612
user7214612

Reputation:

How would you add key values instead of replacing them. Python Dictionary

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 I have tried.

from collections import defaultdict
answer = defaultdict(int)
recordNum = int(input("Which txt files do you want to read from "))
count = 1
counter = 0
counst = 1
countesr = 0
while recordNum > counter:
  with open('txt'+str(count)+'.txt', 'r') as f:
      for 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 the dictionary to be {'cake': '100', 'tart': '60', 'bread': '99'}

but it prints like this  {'cake': '30', 'tart': '50', 'bread': '89'}

Instead of the "cake" value adding with the other cake values from txt file one and two it gets replaced with the latest value. How would I solve this issue.

Upvotes: 1

Views: 169

Answers (2)

Ry-
Ry-

Reputation: 224862

One fun thing you can do is add Counters together:

import csv
from collections import Counter

with open('file.txt', 'r') as f:
    reader = csv.reader(f)
    answer = sum((Counter({k: int(count)}) for k, count in reader), Counter())

print(answer)

Upvotes: 1

Moses Koledoye
Moses Koledoye

Reputation: 78536

You can accumulate the counts using collections.defaultdict:

from collections import defaultdict

answer = defaultdict(int)
with open("file.txt", 'r') as f:
    for line in f:
        k, v = line.split(',')
        answer[k.strip()] += int(v.strip())

# turn values back to string
for k in answer:
    answer[k] = str(answer[k])
print(answer)

If the counts are all positive, you may consider collections.Counter instead.

Upvotes: 1

Related Questions