2015-10-06 71 views
-3

所以我在更新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 
+1

你能提供一个样本,说明你的字典应该看起来像什么吗?另外,请显示'update_customer_dictionary'的代码 – idjaw

+1

将代码格式化为代码,以便更易读 – shafeen

+0

为什么不将'customer_dictionary'创建的字典作为参数传递给'update_customer_dictionary',然后返回已更改的字典? –

回答

0

首先,在customer_dictionarybafile.close()将永远不会因为在此之前,该函数返回执行。您应该颠倒最后两行的顺序,或者更好的是使用with上下文管理器。

其次,当您读取余额文件时,您将所有内容都作为字符串保存。帐户和社会安全号码无关,但您需要将余额转换为浮动。

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> 

我建议在看collections.namedtuple.如果适当定义的东西,你可以改变cdictionary[acct][1]到更加清晰cdictionary[acct].balance

另外,在使用我上面提到的花车时,还有一个可能的舍入问题。对于银行类应用程序,您可能需要考虑使用decimal模块。

+0

有没有使用try和except的方法? –

+0

是的,你可以说'如果在cdictionary中acct',但'try ... except'更好。 Python会检查密钥是否在字典中,不管你是否这样做,所以测试显式地不加任何东西,只是减慢了程序的速度。如果你打算用python编程,你真的应该习惯'try ... except'。但是,当然,如果你刚刚开始,你不会立即这样做。 :-) – saulspatz