2015-10-20 71 views
0

我嘗試使用字典的get方法來避免if-else結構,但該方法返回一個None對象,而我想要一個列表。我的代碼:Python,爲字典獲取方法

dic = {} 
words = ['foo', 'bar'] 
for word in words : 
    long = len(word) 
    dic[long] = dic.get(long, []).append(word) 

我想有(在循環的末尾):

{3:['foo', 'bar']} 

但我有:

AttributeError: 'NoneType' object has no attribute 'append' 

這意味着get返回None對象(默認值)...其中我雖然應該返回一個無效列表,如果該鍵不存在,一個列表填充一些字符串,如果該鍵存在。有任何想法嗎 ?

+0

你可能有一個更容易的時間,如果你只是用['collections.defaultdict'(https://docs.python.org/2.7/library/collections.html#collections.defaultdict)。 – BrenBarn

回答

-1
dic = {} 
words = ['foo', 'bar'] 
for word in words : 
    long = len(word) 
    if (dic.has_key(long)): 
     dic[long].append(word) 
    else: 
     dic[long] = [word]