VisLab

Chris Waters' Weblog

Visualizing the Vislab

Title: dict.get and dict.__index__ revisited
Category: Programming/Python
Posted by:
Previous: Installing GLEW and GLEWpy in Python2.5 on OS X

I did a little more 'thorough' testing on the differences between dict.get(key) and dict[key]. I tested for both keys that do and do not exist, and I seem to have different results than what I did last time =( 
 
It seems dict[key] is about twice as fast as dict.get(key) when the key does exist in the dict. On the other hand, dict[key] + exception handling is twice as slow as dict.get(key) when key is not in dict. Here's the extra twist: checking if the key is in dict and then getting the appropriate value is only slightly slower than simply table[key]. This is something like: 

if key in dict: 
value = dict[key] 
else: 
value = None
or, more elegantly: 
value = None if key not in dict else dict[key]
 
This method is fractionally slower than dict[key] when key is in the table, but it's considerably faster when key is not in the table. Also, this method is consistantly faster than dict.get(key) in both cases. 
 
The script can be found [here
The output for 100,000 iterations of each case can be found [here
 
The output shows the name of each test case followed by the commands executed in the test. Total runtime for each follow each. 
 
I may have done the cases a little naively, but I still think it shows some powerful differences. 

Login Information
Username:
Password:

© Chris Waters. The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by Mississippi State University.