Create dict key only when needed

Michael Hudson mwh at python.net
Thu Feb 13 15:06:31 CET 2003


Helge Stenstrom <helge.stenstrom.NO at SPAM.ericsson.com> writes:

> I'd like to do the following, which doesn't work:
> 
> a = {}
> for key in keys:
>     a[key] += stringFunction()
> 
> where keys contains some duplicates. Put in another way:
> 
> a = {}
> a[17] += "foo"
> a[4711] += "foo"
> a[4711] += "bar"
> would give a = {17: "foo", 4711: "foobar"}
> 
> but that doesn't work, because the keys of the dict must exist before
> the += operator can be used.
> 
> How can this problem be solved in a readible way?
> 
> An ugly solution would be:
[snip]

I think:

def addStuff(dict, key, data):
      dict[key] = dict.get(key, '') + data

is about as good as you can get.

> How can the += syntax be used instead of calling a function?

I don't think it can.  Hmm, you could use a defaultdict class, I
guess.

Cheers,
M.

PS: would one of the German readers of this group based near wherever
    box.de are go and smack them with a clue stick, please?

-- 
  Famous remarks are very seldom quoted correctly.
                                                    -- Simeon Strunsky




More information about the Python-list mailing list