2016-07-30 54 views
0

我想創建一個從字符串到字符串列表的字典。所以我想我會用dict.get()的默認值關鍵字參數這樣:Python dictionary.get()默認返回不工作

read_failures = {} 
for filename in files: 
    try: 
     // open file 
    except Exception as e: 
     error = type(e).__name__ 
     read_failures[error] = read_failures.get(error, []).append(filename) 

所以由我希望read_failures看起來像結尾:

{'UnicodeDecodeError':['234.txt', '237.txt', '593.txt'], 'FileNotFoundError': ['987.txt']} 

我必須使用get()命令,因爲我得到一個KeyError,否則這應該在技術上起作用。如果我在解釋器中逐行執行此操作,它就會起作用。但由於某種原因,在腳本中,read_failures.get(error,[])方法返回None作爲默認值而不是我指定的空白列表。有沒有可能是Python的默認獲取返回不是一個版本?

謝謝!

+4

想想'append'回報。 – user2357112

+0

是的。我是個白癡:)謝謝! – gowrath

回答

2

正如其他意見和答案已經指出,你的問題是,list.append返回None,所以你不能將你的調用結果分配給字典。但是,如果列表已經在字典中,則不需要重新分配它,因爲append將對其進行修改。

所以問題是,如果只有在沒有人的情況下才能向字典添加新列表?粗解決將是使用單獨的if聲明:

if error not in read_failures: 
    read_failures[error] = [] 
read_failures[error].append(filename) 

但是這需要高達字典中關鍵的3個查找,我們可以做的更好。 dict類有一個名爲setdefault的方法,用於檢查給定的鍵是否在字典中。如果不是,它會爲鍵分配給定的默認值。無論如何,字典中的值都會被返回。因此,我們可以做一個行整個事情:

read_failures.setdefault(error, []).append(filename) 

另一種替代解決方案是(在標準庫從collections模塊)使用defaultdict對象,而不是一個正常的字典。 defaultdict構造函數需要一個factory參數,該參數將在任何時候請求一個不存在的密鑰時被調用來創建一個默認值。

所以另一種實現方式是:

from collections import defaultdict 

read_failures = defaultdict(list) 
for filename in files: 
    try: 
     // open file 
    except Exception as e: 
     error = type(e).__name__ 
     read_failures[error].append(filename) 
0

所以這

read_failures[error] = read_failures.get(error, []).append(filename) 

設置read_failures [錯誤]爲無的值,因爲.append方法返回一個無。簡單的修復方法是將其更改爲:

read_failures[error] = read_failures.get(error, []) + [filename] 

謝謝user2357112!