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 :/
None can be used as a dictionary key in Python because it is a hashable object. However, you should avoid using None as a dictionary key if you have to convert your dictionary to JSON as all keys in JSON objects must be strings.
NoneType in Python is a data type that simply shows that an object has no value/has a value of None . You can assign the value of None to a variable but there are also methods that return None .
Method #1 : Using all() + not operator + values() In this, we check for all the values using all function extracted using values function. The not operator is used to inverse the result to check for any of None value.
The dictionary keys and values can be of any type. They can also be None . The key and its value are separated using a colon.
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
Check that self._rooms
is not None
.
Assigning None
as a value to a dict
's key actually works:
In [1]: dict(a=None)
Out[1]: {'a': None}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With