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!
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.
with defaultdict replace
if entry.mygroup == mygroup:
dic[mygroup].append(entry)
with
dic[mygroup].append(entry)
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
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.
with defaultdict replace
if entry.mygroup == mygroup:
dic[mygroup].append(entry)
with
dic[mygroup].append(entry)