Create dict key only when needed

Duncan Booth duncan at
Thu Feb 13 17:29:11 CET 2003

Helge Stenstrom <helge.stenstrom.NO at> wrote in 
news:uel6ci8tm.fsf at

> How can the += syntax be used instead of calling a function?
Here is one way:

>>> class DictWithDefault(dict):
	__slots__ = ['default']
	def __getitem__(self, name):
			return dict.__getitem__(self, name)
		except KeyError:
			return self.default

>>> a = DictWithDefault()
>>> a.default = ""
>>> a[17] += "foo"
>>> a[4711] += "foo"
>>> a[4711] += "bar"
>>> a
{17: 'foo', 4711: 'foobar'}

You would need a bit more code though if the default was to be a mutable 
such as a list.

Duncan Booth                                             duncan at
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?

More information about the Python-list mailing list