Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning NoneType to Dict

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 :/

like image 839
Unistudent Avatar asked May 16 '12 13:05

Unistudent


People also ask

Can none be a dictionary value?

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.

What is NoneType in Python?

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 .

How do you know if a dictionary is not 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.

Can dictionary keys be null Python?

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.


2 Answers

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

like image 189
Jakob Bowyer Avatar answered Sep 19 '22 05:09

Jakob Bowyer


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}
like image 40
Joseph Victor Zammit Avatar answered Sep 21 '22 05:09

Joseph Victor Zammit