Python:使用None作为字典键是否合理? [英] Python: Is it reasonable to use None as a dictionary key?
问题描述
没有似乎是一个字典键,但我想知道这是否会导致麻烦。例如,这样做:
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
我正在使用的实际数据是教育标准。每个标准都与一个内容区域相关联。一些标准也与内容分区相关联。我想制作一个表单 {contentArea:{contentSubArea:[standards]}}
的嵌套字典。其中一些contentSubArea密钥将为无。
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.
推荐答案
任何可哈希值都是有效的Python字典密钥。因此,无是完全有效的候选人。寻找不存在的密钥时不会有混淆 - 无作为密钥的存在不会影响检查是否存在另一个密钥的能力。例如:
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
没有冲突,你可以像普通的一样测试。不应该造成你的问题。标准的1对1键值关联仍然存在,因此您无法在无键中拥有多项功能,但使用无键不应自行构成问题。
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.
这篇关于Python:使用None作为字典键是否合理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!