【发布时间】:2018-04-03 16:18:50
【问题描述】:
我正在尝试将对象附加到默认字典中的值列表:
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'
所以看起来由于某种原因,这些值没有被识别为列表?
有没有办法追加到用作字典或默认字典中的值的列表? (我以前用普通的 dict 试过这个,得到了同样的错误。)
感谢您的帮助!
【问题讨论】:
标签: python dictionary