Python 使用函数更新字典
所以我在用python更新字典时遇到了麻烦。以下是字典的功能:Python 使用函数更新字典,python,dictionary,Python,Dictionary,所以我在用python更新字典时遇到了麻烦。以下是字典的功能: def customer_dictionary(balfilename): d = {} bafile = open(balfilename, 'r') for line in bafile: dic = line.split() d[dic[1]] = [dic[0] , dic[2]] return d bafile.close() 现在我要做的是创建另
def customer_dictionary(balfilename):
d = {}
bafile = open(balfilename, 'r')
for line in bafile:
dic = line.split()
d[dic[1]] = [dic[0] , dic[2]]
return d
bafile.close()
现在我要做的是创建另一个函数,如下所示:
def update_customer_dictionary(cdictionary, transfilename):
transfile = open(transfilename. 'r')
for line in transfile:
act, trans = line.strip().split()
if act in dictionary:
cdictionary[act][1] += float(trans)
else:
cdictionary[act][2] = [act][2]
我似乎不知道如何用这个新函数更新以前函数中创建的字典。cdictionary是以前制作的词典
File 1:
139-28-4313 115 1056.30
706-02-6945 135 -99.06
595-74-5767 143 4289.07
972-87-1379 155 3300.26
814-50-7178 162 3571.94
632-72-6766 182 3516.77
699-77-2796 191 2565.29
File 2:
380 2932.48
192 -830.84
379 2338.82
249 3444.99
466 -88.33
466 2702.32
502 -414.31
554 881.21
首先,在
customer\u dictionary
中,将永远不会执行bafile.close()
行,因为函数在此之前返回。您应该颠倒最后两行的顺序,或者更好地使用上下文管理器
第二,当你读取余额文件时,你将所有内容都保留为一个字符串。账户和社会保险号码也可以,但你需要将余额转换为浮点数
d[dic[1]] = [dic[0] , float(dic[2])]
至于你关于更新字典的问题,可以这样做
def update_customer_dictionary(cdictionary, transfilename):
with open(transfilename) as fin:
for line in fin:
acct, trans = line.strip().split()
try:
cdictionary[acct][1] += float(trans)
except KeyError:
<Print appropriate error message>
def update\u customer\u字典(cdictionary,transfilename):
以open(transfilename)作为fin:
对于fin中的行:
acct,trans=line.strip().split()
尝试:
cdictionary[acct][1]+=浮动(trans)
除KeyError外:
我建议您查看collections.namedtuple.
如果您正确定义内容,可以将cdictionary[acct][1]
更改为更清晰的cdictionary[acct].balance
此外,在使用我上面建议的浮动时,还存在一个潜在的舍入问题。对于银行类型的应用程序,您可能需要考虑使用<代码>十进制< /代码>模块。 你能提供一个你的字典应该是什么样子的例子吗?另外,请显示update\u customer\u dictionary
的代码,将代码格式化为代码,以便更易于阅读。为什么不将customer\u dictionary
创建的字典作为参数传递给update\u customer\u dictionary
,然后返回更改后的词典?在return
语句之后如何关闭bafile
?词典应该是这样的:{'115':['134-28-4313',1056.30]}。更新客户字典的代码是我不知道怎么做的。我不知道如何将文件2添加到令人兴奋的词典中有没有不使用try和except的方法?是的,如果在cdictionary中使用acct,您可以说,但是try。。。除了
更好。Python将检查字典中是否有键,因此显式地执行测试不会增加任何内容,只会降低程序的速度。如果你打算用python编程,你真的应该熟悉try。。。除了
。但是,当然,如果您刚刚开始,您不必立即这样做。:-)