Create dict key only when needed

Nick Vargish nav at adams.patriot.net
Thu Feb 13 10:35:45 EST 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()

a = {}
for key in keys:
    a[key] = a.get(key, '') + stringFunction()

I use things like this pretty frequently. It's not quite as "pretty"
as automatic instantiation of a dictionary element, but does provide
an explicit initial value.

Nick

-- 
# sigmask  |||  version 0.2  |||  2003-01-07  |||  Feed this to your Python.
print reduce(lambda x,y:x+chr(ord(y)-1),'Ojdl!Wbshjti!=obwAqbusjpu/ofu?','')





More information about the Python-list mailing list