查找字典元素的方式及速度;python2 python3下的区别

测试一下python字典中元素查找速度情况

        测试代码如下:

                创建了一个字典,比较 in dict  ; in dict.keys() 和 in set 三种查找方式。

查找字典元素的方式及速度;python2 python3下的区别

        在python2 和python3中的测试结果:

查找字典元素的方式及速度;python2 python3下的区别

查找字典元素的方式及速度;python2 python3下的区别

python2 python3中的异同和结论:

       1.dict.keys()在Python2 Python3中的类型不同, python2 中为list python中为class。所以在Python2中的dict.keys()的速度会慢很多。

       2.Python2中set和in dict的速度相差不多。

       3.Python3中dict  和 dict.keys() 速度相差不多,比set会而更快。

       4.list --> set 也比较耗时。

      结论:在Python2中使用in dict;Python3中使用in dict和dict.keys都可以。