在Python中将None用作字典键是否合理? [英] Is it reasonable to use None as a dictionary key in Python?

查看:132
本文介绍了在Python中将None用作字典键是否合理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎没有人可以用作字典键,但是我想知道这是否会在以后引起麻烦.例如,这有效:

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密钥将为None.

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字典键.因此,没有人是完全有效的候选人.查找不存在的密钥时没有任何困惑-将None作为密钥存在不会影响检查另一个密钥是否存在的能力.例如:

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键-值关联仍然存在,因此None键中不能包含多个内容,但是使用None作为键本身不会造成问题.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆