On this page, I see something interesting:
Note that there is a fast-path for dicts that (in practice) only deal with str keys; this doesn\'t affect the algorith
The C code that underlies the Python dict is optimisted for String keys. You can read about this here (and in the book the blog refers to).
If the Python runtime knows your dict only contains string keys it can do things such as not cater for errors that won't happen with a string to string comparison and ignore the rich comparison operators. This will make the common case of the string key only dict
a little faster. (Update: timing shows it to be more than a little.)
However, it is unlikely that this would make a significant change to the run time of most Python programs. Only worry about this optimisation if you have measured and found dict
lookups to be a bottleneck in your code. As the famous quote says, "Premature optimization is the root of all evil."
The only way to see how much faster things really are, is to time them:
>>> timeit.timeit('a["500"]','a ={}\nfor i in range(1000): a[str(i)] = i')
0.06659698486328125
>>> timeit.timeit('a[500]','a ={}\nfor i in range(1000): a[i] = i')
0.09005999565124512
So using string keys is about 30% faster even compared to int
keys, and I have to admit I was surprised at the size of the difference.