Skip to content
Advertisement

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:

JavaScript

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.

Advertisement

Answer

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:

JavaScript

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement