Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python,字典的get方法_Python_Dictionary_Get - Fatal编程技术网

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]