Create dict key only when needed

Mark McEahern marklists at mceahern.com
Thu Feb 13 09:09:09 EST 2003


> I'd like to do the following, which doesn't work:
> 
> a = {}
> for key in keys:
>     a[key] += stringFunction()

Use setdefault:

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

// m
-






More information about the Python-list mailing list