14

我正在尝试将 None 分配给 dict 中的一个键,但我得到一个 TypeError:

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

我的代码在这里:

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

在它让我分配之前,但不是它不会。它很奇怪 :/

4

4 回答 4

13

例外清楚地表明TypeError: 'NoneType' object does not support item assignment这表明self._rooms实际上是None

编辑:正如你自己所说

self._rooms = {} 

或者

self._rooms = dict()

将做你需要清除字典

于 2012-05-16T13:30:10.283 回答
2

检查self._rooms不是None

将值分配None给 adict的键实际上是有效的:

In [1]: dict(a=None)
Out[1]: {'a': None}
于 2012-05-16T13:30:56.860 回答
1

From reading your comments to Jakob, I gather that the culprit is this line (not posted)

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

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

The cleanest solution to this is:

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

especially since self._rooms appears to have inherited from dict -- so it may have other attributes that you don't want to lose by doing:

self._rooms={}  #Now this is just a dict, no longer has `set_guest` method!
于 2012-05-16T13:45:45.807 回答
0

它可能是在抱怨self._rooms,我怀疑是None

于 2012-05-16T13:30:35.123 回答