Re: Way for see if dict has a key
- From: Fredrik Lundh <fredrik@xxxxxxxxxxxxxx>
- Date: Fri, 30 Jun 2006 17:10:42 +0200
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>
.
- References:
- Way for see if dict has a key
- From: Michele Petrazzo
- Re: Way for see if dict has a key
- From: Bruno Desthuilliers
- Re: Way for see if dict has a key
- From: Michele Petrazzo
- Re: Way for see if dict has a key
- From: André
- Re: Way for see if dict has a key
- From: Michele Petrazzo
- Re: Way for see if dict has a key
- From: Paul McGuire
- Way for see if dict has a key
- Prev by Date: Re: Way for see if dict has a key
- Next by Date: Re: Chapter 9 Tutorial for Classes Not Working
- Previous by thread: Re: Way for see if dict has a key
- Next by thread: Re: Way for see if dict has a key
- Index(es):