【发布时间】:2015-10-06 00:43:47
【问题描述】:
所以我在更新 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 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
【问题讨论】:
-
您能否提供一个示例,说明您的字典应该是什么样子?另外,请出示
update_customer_dictionary的代码 -
将您的代码格式化为代码,使其更具可读性
-
为什么不直接将
customer_dictionary创建的字典作为参数传递给update_customer_dictionary,然后返回修改后的字典? -
在
return声明之后,您如何关闭bafile? -
字典应该是这样的:{'115' : ['134-28-4313' , 1056.30]}。 update_customer_dictionary 的代码是我不知道该怎么做的。我不确定如何将文件 2 添加到令人兴奋的字典中
标签: python dictionary