Jue
Jue

Reputation: 35

List as value of a dictionary gets None after calling __missing__

class ChapterDict(dict):
    def __missing__(self, key):
        res = self[key] = []
        return res

I have this custom Dictionary. If a key does not exist yet, a new key:value pair should be created, whereas the value should be an empty list (of strings). Later on I have my instance

chapters = ChapterDict()

and would like to store values like that.

chapters[processed_key] = chapters[processed_key].append(section)

If I do

print(chapters)

I get {'0': None, '1': None, '2': None, '3': None} as a result, so the keys are right but the list is None.

What's my problem?

Upvotes: 1

Views: 57

Answers (1)

Mureinik
Mureinik

Reputation: 311808

append adds an element to a list and returns None, which you then assign (overwrite) the value for the given key. Drop the assignment and you should be fine:

chapters[processed_key].append(section)

Upvotes: 2

Related Questions