相关疑难解决方法(0)

如果字典键不可用,则返回None

如果它的键存在,我需要一种获取字典值的方法,或者None如果不存在则需要返回.

但是,KeyError如果搜索不存在的密钥,Python会引发异常.我知道我可以检查密钥,但我正在寻找更明确的东西.None如果密钥不存在,有没有办法返回?

python dictionary key nonetype

433
推荐指数
9
解决办法
30万
查看次数

TypeError:get()不带关键字参数

我是Python的新手,我正在尝试基本上创建一个哈希表,检查一个键是否指向表中的值,如果不是,则将其初始化为空数组.我的代码的违规部分是行:

converted_comments[submission.id] = converted_comments.get(submission.id, default=0)
Run Code Online (Sandbox Code Playgroud)

我收到错误:

TypeError: get() takes no keyword arguments
Run Code Online (Sandbox Code Playgroud)

但是在文档(以及各种示例代码)中,我可以看到它确实采用了一个默认参数:

https://docs.python.org/2/library/stdtypes.html#dict.get http://www.tutorialspoint.com/python/dictionary_get.htm

以下是get()方法的语法:

dict.get(key,default = None)

在堆栈上没有任何关于这个,所以我认为这是一个初学者的错误?

python

49
推荐指数
3
解决办法
5万
查看次数

标签 统计

python ×2

dictionary ×1

key ×1

nonetype ×1