class Dict(dict): def __getitem__(self, key): try: return super(Dict, self).__getitem__(key) except KeyError: return key >>> a = Dict() >>> a[1] 1 >>> a[1] = 'foo' >>> a[1] foo
This works if you need to support Python <2.5 (which added the __missing__ method mentioned by @katrielalex).
source share