Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

append to list in defaultdict

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!

like image 720
CodingCat Avatar asked Sep 07 '12 11:09

CodingCat


People also ask

What does Defaultdict list do in Python?

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.

Is Defaultdict slower than dict?

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);

Can you append to a dictionary?

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.

What does the Defaultdict () function do?

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.


1 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.

like image 85
Lev Levitsky Avatar answered Oct 11 '22 01:10

Lev Levitsky