Python,字典的get方法
我尝试使用字典的Python,字典的get方法,python,dictionary,get,Python,Dictionary,Get,我尝试使用字典的get方法来避免使用if-else结构,但该方法返回一个None对象,而我需要一个列表。我的代码: dic = {} words = ['foo', 'bar'] for word in words : long = len(word) dic[long] = dic.get(long, []).append(word) 我想要(在循环结束时): 但我有: AttributeError: 'NoneType' object has no attribute 'a
get
方法来避免使用if-else
结构,但该方法返回一个None
对象,而我需要一个列表。我的代码:
dic = {}
words = ['foo', 'bar']
for word in words :
long = len(word)
dic[long] = dic.get(long, []).append(word)
我想要(在循环结束时):
但我有:
AttributeError: 'NoneType' object has no attribute 'append'
这意味着
get
返回了一个None
对象(默认值)。。。我认为如果键不存在,它应该返回一个空列表;如果键存在,它应该返回一个填充了一些字符串的列表。有什么想法吗?如果你只是使用它,你可能会过得更轻松。
dic = {}
words = ['foo', 'bar']
for word in words :
long = len(word)
if (dic.has_key(long)):
dic[long].append(word)
else:
dic[long] = [word]
dic = {}
words = ['foo', 'bar']
for word in words :
long = len(word)
if (dic.has_key(long)):
dic[long].append(word)
else:
dic[long] = [word]