Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it reasonable to use None as a dictionary key in Python?

None seems to work as a dictionary key, but I am wondering if that will just lead to trouble later. For example, this works:

>>> x={'a':1, 'b':2, None:3}
>>> x
{'a': 1, None: 3, 'b': 2}
>>> x[None]
3

The actual data I am working with is educational standards. Every standard is associated with a content area. Some standards are also associated with content subareas. I would like to make a nested dictionary of the form {contentArea:{contentSubArea:[standards]}}. Some of those contentSubArea keys would be None.

In particular, I am wondering if this will lead to confusion if I look for a key that does not exist at some point, or something unanticipated like that.

like image 944
japhyr Avatar asked Aug 11 '11 17:08

japhyr


People also ask

Can None be a Python dictionary key?

None is not special in any particular way, it's just another python value. Its only distinction is that it happens to be the return value of a function that doesn't specify any other return value, and it also happens to be a common default value (the default arg of dict.

Which Cannot be used as a key in Python dictionaries?

We can use integer, string, tuples as dictionary keys but cannot use list as a key of it .

Can a dictionary have a null as a key?

EDIT: Real answer to the question actually being asked: Why can't you use null as a key for a Dictionary<bool?, string>? The reason the generic dictionary doesn't support null is because TKey might be a value type, which doesn't have null.

What is a valid key for Python dictionary?

Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable.


2 Answers

Any hashable value is a valid Python Dictionary Key. For this reason, None is a perfectly valid candidate. There's no confusion when looking for non-existent keys - the presence of None as a key would not affect the ability to check for whether another key was present. Ex:

>>> d = {1: 'a', 2: 'b', None: 'c'}
>>> 1 in d
True
>>> 5 in d
False
>>> None in d
True

There's no conflict, and you can test for it just like normal. It shouldn't cause you a problem. The standard 1-to-1 Key-Value association still exists, so you can't have multiple things in the None key, but using None as a key shouldn't pose a problem by itself.

like image 87
g.d.d.c Avatar answered Oct 16 '22 10:10

g.d.d.c


You want trouble? here we go:

>>> json.loads(json.dumps({None:None}))
{u'null': None}

So yea, better stay away from json if you do use None as a key. You can patch this by custom (de/)serializer, but I would advise against use of None as a key in the first place.

like image 21
Maciej Urbański Avatar answered Oct 16 '22 11:10

Maciej Urbański