Way for see if dict has a key
Paul McGuire
ptmcg at austin.rr._bogus_.com
Fri Jun 30 10:07:28 EDT 2006
"Michele Petrazzo" <michele.petrazzo at TOGLIunipex.it> wrote in message
news:zZ7pg.21792$zy5.445667 at twister1.libero.it...
> > when we expect that the key will most often be in my_dict so that
> > exception will be raised rarely
>
> I didn't thought this because if I think that a key aren't in a dict, I
> use dict.get(key, default)
>
Another factor to consider is if "default" is not something simple like 0 or
None, but is an object constructed and initialized with some expensive
initialization code (like access to a database). In this case:
dict.get(key, ExpensiveObjectToCreate())
always creates the default value, and if the key does not exist, then
promptly drops it on the floor.
In such a case you'd be better off with one of the "check for existence"
patterns, which only creates the default value if you *know* you're going to
need it.
-- Paul
More information about the Python-list
mailing list