Add to list in defaultdict

I am trying to add objects to lists that are values ​​in 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) 

Therefore, I want to collect all the records belonging to one group in this dictionary, using the group name as a key and a list of all related objects as a value.

But the above code raises an AttributeError:

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

It looks like for some reason the values ​​are not recognized as lists?

Is there a way to add to lists used as values ​​in a dictionary or defaultdict? (I tried this with the usual dict before, and got the same error.)

Thanks for any help! Lastalda

+7
source share
1 answer

Try

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

Same as using append on any list. append returns nothing, so when you assign the result to dic[mygroup] , it turns into None . The next time you try to add to it, you will receive an error message.

+14
source

All Articles