Today, the Python dictionary has been specifically tested for performance results in comparison with various methods.
The test code is as follows:
1 defdict_traverse ():2 fromTimeImportClock3My_dict = {'name':'Jim',' Age':' -','Height':'180cm','Weight':'60kg'}4 5T_start =clock ()6 forKeyinchMy_dict:#worst-performing notation. No optimization7 Print 'Type01.01:%s---%s'%(Key, My_dict[key])8T1 =clock ()9 Ten forKeyinchMy_dict:#The performance is better, the visible get () method is optimized. One Print 'Type01.02:%s---%s'%(Key, My_dict.get (key)) At2 =clock () - - forKeyinchMy_dict.keys ():#the keys () method is also optimized. the Print 'Type02.01:%s---%s'%(Key, My_dict[key]) -T3 =clock () - - forKeyinchMy_dict.keys ():# + Print 'Type02.02:%s---%s'%(Key, My_dict.get (key)) -T4 =clock () + A forKey, ValueinchMy_dict.items ():#standard notation, performance best written at Print 'Type03:%s---%s'%(key, value) -T5 =clock () - - forKey, ValueinchMy_dict.iteritems ():#The performance is higher, there is a small loss. - Print 'Type04:%s---%s'%(key, value) -T6 =clock () in - forKey, ValueinchZip (My_dict.iterkeys (), My_dict.itervalues ()):#poor performance. to Print 'Type05:%s---%s'%(key, value) +T7 =clock () - the Print '********** Time cost ******************' * Print 'Type01.01--Total time:', t1-T_start $ Print 'Type01.02--Total time:', t2-T1Panax Notoginseng Print 'Type02.01--Total time:', t3-T2 - Print 'Type02.02--Total time:', t4-T3 the Print 'TYPE03--Total time:', t5-T4 + Print 'TYPE04--Total time:', t6-T5 A Print 'Type05--Total time:', t7-T6 the + - $ if __name__=='__main__': $Dict_traverse ()
After several runs, it can be found that different writing, time-consuming is a difference.
The comparison results are as shown.
In contrast, it can be found that:
For dictionary traversal, the following is recommended, performance is optimal.
1 for inch My_dict.items (): 2 Print
Python Learning Notes _ Dictionary (Dict) _ Traversal _ Different Methods _ Performance test comparison