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!
The Python defaultdict type behaves almost exactly like a regular Python dictionary, but if you try to access or modify a missing key, then defaultdict will automatically create the key and generate a default value for it. This makes defaultdict a valuable option for handling missing keys in dictionaries.
It depends on the data; setdefault is faster and simpler with small data sets; defaultdict is faster for larger data sets with more homogenous key sets (ie, how short the dict is after adding elements);
Appending element(s) to a dictionaryTo append an element to an existing dictionary, you have to use the dictionary name followed by square brackets with the key name and assign a value to it.
A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) that takes no arguments and provides the default value for a nonexistent key. A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With