Python:关于高效使用字典的清单
字典(dict)对象是 Python 最常用的数据结构,社区曾有人开玩笑地说:”Python 企图用字典装载整个世界”,字典在 Python 中的重要性不言而喻,这里整理了几个关于高效使用字典的清单,助你代码更加 Pythonic。
1、用 in 关键字检查 key 是否存在
Python之禅中有一条开发哲学是:
There should be one— and preferably only one —obvious way to do it.
尽量找一种,最好是唯一种显而易见的解决方案。Python2 中判断某个 key 是否存在字典中可使用has_key方法,另外一种方式是使用in关键字。但是强烈推荐使用后者,因为 in 的处理速度更快,另外一个原因是 has_key 这个方法在 Python3 被移除了,要想同时兼容py2和py3两个版本的代码,用 in 是最好的选择。
bad

good

2、用 get 获取字典中的值
关于获取字典中的值,一种简单的方式就是用d.[x]访问该元素,但是这种情况在 key 不存在的情况下会报 KeyError 错误,当然你可以先用 in 操作检查 key 是否在字典中再获取,不过这种方式不符合 Python 之禅中说的:
Simple is better than complex.
Flat is better than nested.
好的代码应该是简单易懂的,扁平的代码结构更加可读。我们可以使用 get 方法来代替 if … else
bad

good
print(d.get("name", "default"))
3、用 setdefault 为字典中不存在的 key 设置缺省值

在做分类统计时,希望把同一类型的数据归到字典中的某种类型中,比如上面代码,把相同类型的事物用列表的形式重新组装,得到新的字典

普通的方式就是先判断 key 是否已经存在,如果不存在则要先用列表对象进行初始化,再执行后续操作。而更好的方式就是使用字典中的 setdefault 方法。
bad

good

setdefault的作用是:
如果 key 存在于字典中,那么直接返回对应的值,等效于 get 方法
如果 key 不存在字典中,则会用 setdefault 中的第二个参数作为该 key 的值,再返回该值。
4、用 defaultdict 初始化字典对象
如果不希望 d[x] 在 x 不存在时报错,除了在获取元素时使用 get 方法之外,另外一种方式是用 collections 模块中的 defaultdict,在初始化字典的时候指定一个函数,其实 defaultdit 是 dict 的子类。

当 key 不存在于字典中时,list 函数将被调用并返回一个空列表赋值给 d[key],这样一来,你就不用担心调用 d[k] 会报错了。
5、用 fromkeys 将列表转换成字典

6、用字典实现 switch … case 语句
Python 中没有 switch … case 语句,这个问题Python之父龟叔表示这个语法过去没有,现在没有,以后也不会有。因为Python简洁的语法完全可以用 if … elif 实现。如果有太多的分支判断,还可以使用字典来代替。

good

7、使用 iteritems 迭代字典中的元素
python提供了几种方式迭代字典中的元素,第一种是使用 items 方法:

items 方法返回的时(key ,value)组成的列表对象,这种方式的弊端是迭代超大字典的时候,内存瞬间会扩大两倍,因为列表对象会一次性把所有元素加载到内存,更好的方式是使用 iteritems

iteritems 返回的是迭代器对象,迭代器对象具有惰性加载的特性,只有真正需要的时候才生成值,这种方式在迭代过程中不需要额外的内存来装载这些数据。注意 Python3 中,只有 items 方法了,它等价于 Python2 中的 iteritems,而 iteritems 这个方法名被移除了。
8、使用字典推导式
推导式是个绝妙的东西,列表推导式一出,map、filter等函数黯然失色,自 Python2.7以后的版本,此特性扩展到了字典和集合身上,构建字典对象无需调用 dict 方法。
bad

good
