Create dict key only when needed

Padraig at Linux.ie Padraig at Linux.ie
Thu Feb 13 09:12:55 EST 2003


Helge Stenstrom wrote:
> I'd like to do the following, which doesn't work:
> 
> a = {}
> for key in keys:
>     a[key] += stringFunction()
> 
> but that doesn't work, because the keys of the dict must exist before
> the += operator can be used.

help({}.setdefault)

> How can this problem be solved in a readible way?
> 
> An ugly solution would be:
> 
> # -------- Start of example  ---------
> def addStuff(dict, key, data):
>     if dict.has_key(key):
>         dict[key] += data
>     else:
>         dict[key] = data
> 
> How can the += syntax be used instead of calling a function?

you can subclass the dict

Pádraig.





More information about the Python-list mailing list