Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

for line in open('transactions.dat','r'):
    item=line.rstrip('
').split(',')
    custid=item[2]
    amt=item[4]
    if custid in cust:
        amt1=int(cust[custid])+int(amt)
        cust[custid]=amt1
    else:
        cust[custid]=[amt]

well i am trying to check if customer id already is there in dictionary then simply add the previous amount and new amount in that customer. Otherwise add that amount in a new position in list. But i am getting error:

 Traceback (most recent call last):
File "<pyshell#74>", line 7, in <module>
amt1=int(cust[custid])+int(amt)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'                    

some transaction data is like:

101300101,2016-09-03,376248582,1013,10.92

109400132,2016-09-03,391031719,1094,36.72

136100107,2016-09-03,391031719,1361,28.77
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
139 views
Welcome To Ask or Share your Answers For Others

1 Answer

Did you try using defaultdict? It would make your job much easier.

from collections import defaultdict

cust = defaultdict(int)
for line in open('transactions.dat','r'):
    item=line.rstrip('
').split(',')
    custid=item[2]
    amt=item[4]

    cust[custid] += float(amt)

and why do you try to cast amt to int? Looks like it's not an integer in the sample lines you posted. If you really want to use integer change float(amt) to int(float(amt)).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...