Python defaultdict that does not insert missing values

You can subclass dict and implement __missing__:

class missingdict(dict):
    def __missing__(self, key):
        return 'default'  # note, does *not* set self[key]

Demo:

>>> d = missingdict()
>>> d['foo']
'default'
>>> d
{}

You could subclass defaultdict too, you'd get the factory handling plus copy and pickle support thrown in:

from collections import defaultdict

class missingdict(defaultdict):
    def __missing__(self, key):
        return self.default_factory() 

Demo:

>>> from collections import defaultdict
>>> class missingdict(defaultdict):
...     def __missing__(self, key):
...         return self.default_factory() 
... 
>>> d = missingdict(list)
>>> d['foo']
[]
>>> d
defaultdict(<type 'list'>, {})

but, as you can see, the __repr__ does lie about its name.