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

前端 未结 6 2230
没有蜡笔的小新
没有蜡笔的小新 2021-02-06 20:15

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, N         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-06 20:59

    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.

提交回复
热议问题