Novice Tip: if key in {}, not {}.has_key()

2009-08-04

I’m sure a lot of you know this already, but it’s always nice to share some information on the off-chance that someone doesn’t. I am actively working on a library and, when profiling the execution of the tokenizing methods, I noticed a large inefficiency with the has_key() function that only gets worse as the dictionary grows. I switched this to an if key in {} format and efficiency boosted by approximately 54%.

The reasoning is that Python’s in-operator is an “under-the-hood C-level call,” meaning that it operates at a much swifter pace as opposed to the has_key() Python way [1].

In subsequent reading I found a nice guide that, if you found this helpful, you might learn a thing or two from—Code Like a Pythonista: Idiomatic Python (Goodger, David). I personally did not know about Python’s interactive “_"—what a useful little character!

[1] Lundh, Fredrik. "dict.has_key(x) versus ‘x in dict’” 6 Dec 2006. Web. \<http://mail.python.org/pipermail/python-list/2006-December/588627.html>.

← all posts

michael schade

I built out engineering and operations teams at Stripe as employee #20 from 2012 to 2019; now I'm working on something new. I like helping people, photography, reading, gym, traveling, and learning new things. Say hi! 🏳️‍🌈