Pythonic way for missing dict keys

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Fri Jul 20 20:20:56 EDT 2007


On Fri, 20 Jul 2007 19:08:57 +0000, Alex Popescu wrote:

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

[snip three versions]

Others have already mentioned the collections.defaultdict type, however it
seems people have forgotten about the setdefault method of dictionaries.

value = somedict.setdefault(key, defaultvalue)

The disadvantage of setdefault is that the defaultvalue has to be created
up front. The disadvantage of collections.defaultdict is that the "default
factory" function takes no arguments, which makes it rather less than
convenient. One can work around this using global variables:

# The default value is expensive to calculate, and known
# only at runtime.

>>> expensivefunction = lambda x: str(x)
>>> D = collections.defaultdict(lambda : expensivefunction(context))

# lots of code goes here...

# set context just before fetching from the default dict
>>> context = 42
>>> value = D['key']
>>> print value, D
42 defaultdict(<function <lambda> at 0xb7eb4fb4>, {'key': '42'})

but one should be very leery of relying on global variables like that.

That suggests the best solution is something like this:

def getdefault(adict, key, expensivefunction, context):
    if key in adict:
        return adict[key]
    else:
        value = expensivefunction(context)
        adict[key] = value
        return value



-- 
Steven.




More information about the Python-list mailing list