Should you use None as a dictionary key in Python

avatar

Borislav Hadzhiev

Last updated: Jun 15, 2022

banner

Photo from Unsplash

Should you use None as a dictionary key in Python #

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.

main.py
my_dict = {'name': 'Alice', None: 30} print(my_dict[None]) # 👉️ 30 print(None in my_dict) # 👉️ True

Most of the immutable built-in objects in Python are hashable, whereas mutable objects are unhashable.

If an object is hashable, then it can be used as a key in a dictionary and as an element in a set, because these data structures use the hash value internally.

Hashable objects include - None, str, int, bool, tuple, frozenset.

Unhashable objects include - list, dict, set.

Note that tuples and frozensets are only hashable if their elements are hashable.

The None object is hashable and can be used as a dictionary key. However, you should avoid using it if you have to convert your dictionary to JSON.

main.py
import json my_dict = {'name': 'Alice', None: None} print(my_dict) # 👉️ {'name': 'Alice', None: None} my_json = json.dumps(my_dict) print(my_json) # 👉️ '{"name": "Alice", "null": null}' my_dict_again = json.loads(my_json) print(my_dict_again) # 👉️ {'name': 'Alice', 'null': None}

The json.dumps method converts a Python object to a JSON formatted string.

The json.loads method parses a JSON string into a native Python object.

We started with a Python object that has a None key and a None value.

When we converted the object to JSON, both the key and the value got converted to null.

When we parsed the JSON string into a Python object, the value got converted to None, but the key is still the string null.

This is because JSON keys must be of type string. If we pass a key of any other type to the json.dumps() method, the key automatically gets converted to a string.

Once the key is converted to a string, parsing the JSON string will return a string key in the Python object.

As you would expect trying to access a None key in the new dictionary would raise a KeyError as the key has now been renamed to null.

main.py
my_dict = {'name': 'Alice', 'null': None} # ⛔️ KeyError: None print(my_dict[None])

This is why you should generally avoid using None as a dictionary key when you have to use the json module as it is more trouble than it is worth.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.