Dictionaries with variable default.

Antoon Pardon antoon.pardon at rece.vub.ac.be
Tue Nov 4 14:21:30 CET 2014


Op 03-11-14 om 12:09 schreef Chris Angelico:
> On Mon, Nov 3, 2014 at 10:04 PM, Antoon Pardon
> <antoon.pardon at rece.vub.ac.be> wrote:
>> Is it possible to have a default dictionary where the default is dependant
>> on the key?
>>
>> I was hoping something like this might work:
>>>>> m = defaultdict(lambda key: key+1)
>> But it obviously doesn't:
>>>>> m[3]
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in <module>
>> TypeError: <lambda>() takes exactly 1 argument (0 given)
> Yes, but not with the defaultdict. Instead, just implement __missing__:
>
> class KeyPlusOne(dict):
>     def __missing__(self, key): return key+1
>
> ChrisA

So How should I call this:

class ...dict(dict):
    def __init__(self, fun):
        self.fun = fun

    def __missing__(self, key):
       return self.fun(key)





More information about the Python-list mailing list