【问题标题】:append to list in defaultdict附加到 defaultdict 中的列表
【发布时间】: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


    【解决方案1】:

    试试

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

    这与您在任何列表中使用 append 的方式相同。 append 不返回任何内容,因此当您将结果分配给dic[mygroup] 时,它会变成None。下次尝试追加时,您会收到错误消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-02
      • 2021-07-12
      • 1970-01-01
      • 2012-12-20
      • 1970-01-01
      • 2013-09-26
      • 2013-01-28
      • 1970-01-01
      相关资源
      最近更新 更多