Way for see if dict has a key

Fredrik Lundh fredrik at pythonware.com
Fri Jun 30 11:10:42 EDT 2006


Paul McGuire wrote:


> 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.

unless you're targeting 2.5 or later, in which case you can use the 
defaultdict class:

 >>> import collections

 >>> def ExpensiveObjectToCreate():
...     print "creating an expensive object"
...     return "expensive object"
...
 >>> d = collections.defaultdict(ExpensiveObjectToCreate)
 >>> d["key"]
creating an expensive object
'expensive object'
 >>> d["key"]
'expensive object'

or, if you prefer, the new __missing__ hook:

 >>> class mydict(dict):
...     def __missing__(self, key):
...             print "add new object base on", key
...             value = "new object"
...             self[key] = value
...             return value
...
 >>> d = mydict()
 >>> d["key"]
add new object base on key
'new object'
 >>> d["key"]
'new object'

</F>




More information about the Python-list mailing list