【发布时间】:2015-10-20 17:48:30
【问题描述】:
我尝试使用字典的get 方法来避免if-else 结构,但是该方法返回一个None 对象,而我想要一个列表。我的代码:
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 对象(默认值)......我虽然如果键不存在它应该返回一个空列表,如果键存在则一个列表填充一些字符串。有什么想法吗?
【问题讨论】:
-
如果您只使用
collections.defaultdict,您可能会更轻松。
标签: python dictionary get