Assigning NoneType to a Dict

I try to assign None to a key in a dict, but I get 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 allows me to appoint, but will not. Strange: /

+7
source share
4 answers

The TypeError: 'NoneType' object does not support item assignment clearly indicated by the TypeError: 'NoneType' object does not support item assignment , this means 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

+8
source

In reviewing my comments on Jacob, I understand that the culprit is this line (not published)

 d = self._rooms self._rooms = d.clear() 

d.clear() will clear the d (and self._rooms ) self._rooms and return None . Thus, everything said is done, d is an empty dictionary, and self._rooms is None .

The cleanest solution for this:

 self._rooms.clear() #No need for assignment here! 

moreover, self._rooms seems to be inherited from dict - so it may have other attributes that you don't want to lose:

 self._rooms={} #Now this is just a dict, no longer has `set_guest` method! 
+1
source

He probably complains about self._rooms , which I suspect is None .

0
source

Make sure self._rooms not None .

Assigning None as the value for the dict key really works:

 In [1]: dict(a=None) Out[1]: {'a': None} 
0
source

All Articles