如果键退出,尝试增加列表值

时间:2016-11-01 21:52:36

标签: python dictionary

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

我正在尝试检查客户ID是否已存在于字典中,然后只需在该客户中添加之前的金额和新金额。否则,将该金额添加到列表中的新位置。但我得到错误:

 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'                    

某些交易数据如下:

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

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

136100107,2016-09-03,391031719,1361,28.77

1 个答案:

答案 0 :(得分:0)

您尝试使用defaultdict了吗?这会让你的工作变得更轻松。

from collections import defaultdict

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

    cust[custid] += float(amt)

为什么要尝试将amt转换为int?看起来它不是您发布的示例行中的整数。如果您确实想要将整数更改float(amt)用于int(float(amt))

相关问题