append to list in defaultdict

Question:

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!

Asked By: CodingCat

||

Answers:

Try

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

That’s the same way you use append on any list. append doesn’t return anything, so when you assign the result to dic[mygroup], it turns into None. Next time you try to append to it, you get the error.

Answered By: Lev Levitsky

with defaultdict replace

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

with

dic[mygroup].append(entry)
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.