Cod*_*Cat 10 python dictionary
我正在尝试将对象追加到defaultdict中的值列表:
dic = defaultdict(list)
groups = ["A","B","C","D"]
# data_list is a list of objects from a self-defined class.
# Among others, they have an attribute called mygroup
for entry in data_list:
for mygroup in groups:
if entry.mygroup == mygroup:
dic[mygroup] = dic[mygroup].append(entry)
Run Code Online (Sandbox Code Playgroud)
所以我想收集属于这个字典中一个组的所有条目,使用组名作为键,并将所有相关对象的列表作为值.
但是上面的代码引发了一个AttributeError:
dic[mygroup] = dic[mygroup].append(entry)
AttributeError: 'NoneType' object has no attribute 'append'
Run Code Online (Sandbox Code Playgroud)
所以看起来由于某种原因,值不被识别为列表?
有没有办法附加到字典或defaultdict中用作值的列表?(我之前用普通的dict尝试过这个,并得到了同样的错误.)
谢谢你的帮助!
Lev*_*sky 18
尝试
if entry.mygroup == mygroup:
dic[mygroup].append(entry)
Run Code Online (Sandbox Code Playgroud)
这与您append在任何列表中使用的方式相同.append不会返回任何内容,因此当您将结果分配给dic[mygroup]它时,它会变成None.下次尝试追加时,会出现错误.