2015-10-06 44 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