我正在尝试将对象附加到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)
所以我想要收集这个字典中属于一个组的所有条目,使用组名作为键,将所有相关对象的列表作为值。但是上面的代码会引发AttributeError错误:
dic[mygroup] = dic[mygroup].append(entry)
AttributeError: 'NoneType' object has no attribute 'append'
看起来由于某种原因,这些值没有被识别为列表?
有没有一种方法可以将用作字典或defaultdict中的值的列表附加到其中? (我以前尝试过使用普通字典,但得到了相同的错误。)
谢谢任何帮助!