简体   繁体   English

append 在默认字典中列出

[英]append to list in defaultdict

I'm trying to append objects to lists which are values in a defaultdict:我正在尝试将 append 对象添加到默认字典中的值列表中:

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)

So I want to collect all entries that belong to one group in this dictionary, using the group name as key and a list of all concerned objects as value.所以我想收集属于这个字典中一个组的所有条目,使用组名作为键,所有相关对象的列表作为值。

But the above code raises an AttributeError:但是上面的代码引发了一个 AttributeError:

    dic[mygroup] = dic[mygroup].append(entry)
AttributeError: 'NoneType' object has no attribute 'append'

So it looks like for some reason, the values are not recognized as lists?所以看起来由于某种原因,这些值没有被识别为列表?

Is there a way to append to lists used as values in a dictionary or defaultdict?有没有办法将 append 列表用作字典或 defaultdict 中的值? (I've tried this with a normal dict before, and got the same error.) (我以前用普通的 dict 试过这个,得到了同样的错误。)

Thanks for any help!谢谢你的帮助!

Try 尝试

if entry.mygroup == mygroup:
    dic[mygroup].append(entry)

That's the same way you use append on any list. 这与你在任何列表中使用append方式相同。 append doesn't return anything, so when you assign the result to dic[mygroup] , it turns into None . append不返回任何内容,因此当您将结果分配给dic[mygroup] ,它将变为None Next time you try to append to it, you get the error. 下次尝试追加时,会出现错误。

with defaultdict replace用 defaultdict 替换

if entry.mygroup == mygroup:
    dic[mygroup].append(entry)

with

dic[mygroup].append(entry)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM