Assigning NoneType to Dict

Unistudent picture Unistudent · May 16, 2012 · Viewed 36.9k times · Source

I am trying to assign None to a key in a dict, but I am getting a TypeError:

self._rooms[g[0]] = None
TypeError: 'NoneType' object does not support item assignment

My code is here:

r = open(filename, 'rU')
    for line in r:
        g = line.strip().split(',')
        if len(g) > 1:
            r1 = g[0]
            h = Guest(g[1], str2date(g[2]), str2date(g[3]))
            self._rooms.set_guest(r1, h)
        else:
            self._rooms[g[0]] = None
    r.close()

Before it would let me assign, but not it won't. It is strange :/

Answer

Jakob Bowyer picture Jakob Bowyer · May 16, 2012

The exception clearly states TypeError: 'NoneType' object does not support item assignment this suggests that self._rooms is actually None

Edit: As you said yourself

self._rooms = {} 

or

self._rooms = dict()

Will do what you need to clear the dict