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

前端 未结 6 2222
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  忘了有多久
    2021-02-06 20:59

    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.get(), for instance).

    You won't cause any run-time conflicts using such a key, but you should ask yourself if that's really a meaningful value to use for a key. It's often more helpful, from the point of view of reading code and understanding what it does, to use a designated instance for special values. Something like:

    NoSubContent = SubContentArea(name=None)
    
    {"contentArea": 
        {NoSubContent:[standards], 
         SubContentArea(name="Fruits"): ['apples', 'bananas']}}
    

提交回复
热议问题