5.21 字典访问不存在的key时不再报错 ================================== .. image:: http://image.iswbm.com/20200804124133.png 当一个字典里没有某个 key 时,此时你访问他是会报 KeyError 的。 .. code:: python >>> profile={} >>> profile["age"] Traceback (most recent call last): File "", line 1, in KeyError: 'age' 这里有一个小技巧,使用 collections 的 defaultdict 方法,可以帮你处理这个小问题,当你访问一个不存在的 key 时,会返回默认值。 defaultdict 接收一个工厂方法,工厂方法返回的对象就是字典的默认值。 常用的工厂方法有,我们常见的 int,str,bool 等 .. code:: python >>> a=int() >>> a 0 >>> >>> b=str() >>> b '' >>> >>> c=bool() >>> c False 因为 defaultdict 可以这样子用。 .. code:: python >>> import collections >>> profile=collections.defaultdict(int) >>> profile defaultdict(, {}) >>> profile["age"] 0 >>> profile=collections.defaultdict(str) >>> profile defaultdict(, {}) >>> profile["name"] '' 当然既然是工厂方法,你也可以使用 lambda 匿名函数来实现自定义的效果,比如我们使用 str 就会设置一个空字符串,但这并不是我想要的,我想要的是设置一个其他字符串,你就可以像下面这样子。 .. code:: python >>> info=collections.defaultdict(lambda: "default value") >>> info defaultdict( at 0x10ff10488>, {}) >>> >>> info["msg"] 'default value'