I’m trying to append objects to lists which are values in a 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)
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:
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?
(I’ve tried this with a normal dict before, and got the same error.)
Thanks for any help!
Try
That’s the same way you use
appendon any list.appenddoesn’t return anything, so when you assign the result todic[mygroup], it turns intoNone. Next time you try to append to it, you get the error.