Kam Kam - 1 month ago 6
Python Question

adding string objects which are numbers in dictionary

for line in open('transactions.dat','r'):
item=line.rstrip('\n')
item=item.split(',')
custid=item[2]
amt=item[4]
if custid in cust1:
a=cust1[custid]
b=amt
c=(a)+(b)
print(cust1[custid]+" : "+a+" :"+b+":"+c)
break
else:
cust1[custid]=amt



Output:
85.91 : 85.91 :85.91:85.9185.91



Well above is my code what i want is


  • when i read from a file i want to add the customer amount with same
    id.

  • Secondly there should not be repetition of customer id in my

    dictionary.

    so i am trying to add customer amount which is C but it gives me appended string instead of adding the two. You can see in the last part of my output which is value of c. So how do i add the values.



Sample transaction data:

109400182,2016-09-10,119257029,1094,40.29

109400183,2016-09-10,119257029,1094,9.99

377700146,2016-09-10,119257029,3777,49.37

276900142,2016-09-10,135127654,2769,23.31

276900143,2016-09-10,135127654,2769,25.58

Answer

You reading strings, instead of floats, from the file. Use this amt=float(item[4]) to convert strings representing numbers to floats, and then print(str(cust1[custid])+" : "+str(a)+" :"+str(b)+":"+str(c)) to print out.

Comments