Pythonic way for missing dict keys

Alex Popescu the.mindstorm.mailinglist at gmail.com
Fri Jul 20 15:08:57 EDT 2007


Hi all!

I am pretty sure this has been asked a couple of times, but I don't seem 
to find it on the archives (Google seems to have a couple of problems 
lately).

I am wondering what is the most pythonic way of dealing with missing 
keys and default values.

According to my readings one can take the following approaches:

1/ check before (this has a specific name and acronym that I haven't 
learnt yet by heart)

if not my_dict.has_key(key):
  my_obj = myobject()
  my_dict[key] = my_obj
else:
  my_obj = my_dict[key]

2/ try and react on error (this has also a specific name, but...)

try:
  my_obj = my_dict[key]
except AttributeError:
  my_obj = myobject()
  my_dict[key] = my_obj

3/ dict.get usage:

my_obj = my_dict.get(key, myobject())

I am wondering which one is the most recommended way? get usage seems 
the clearest, but the only problem I see is that I think myobject() is 
evaluated at call time, and so if the initialization is expensive you 
will probably see surprises.

thanks in advance,
./alex
--
.w( the_mindstorm )p.




More information about the Python-list mailing list