美文网首页
python跳过dict不存在的key

python跳过dict不存在的key

作者: aTrahir | 来源:发表于2018-08-07 17:45 被阅读0次

    天天都有新坑。

    坑一:

    这次是遍历一组dict对象,其中的key值不规律,有的全有的缺,如果正常读取遇到不存在的key值时就会报错:KeyError

    解决方案是用 dict 对象的 get() 方法,dict.get(key,default=None),来判断key值是否存在,不存在的返回None

    坑二:

    如果原封不动输入

    dict.get(key,default=None)
    

    Python会继续报错:TypeError: get() takes no keyword arguments,get()方法不接受关键字参数

    原因是Python C-level APIs developed,有部分内置方法实际上没有参数名称,只能通过在指定位置上上传参数,传入名称则无法识别

    >>> d = {1: 2}
    >>> d.get(0, default=0)
    Traceback (most recent call last):File "", line 1, in
    TypeError: get() takes no keyword arguments
    >>> d.get(0, 0)
    

    相关文章

      网友评论

          本文标题:python跳过dict不存在的key

          本文链接:https://www.haomeiwen.com/subject/xvbavftx.html