expanding a variable to a dict

Max M maxm at mxm.dk
Fri Apr 4 00:44:56 CEST 2008


idle skrev:

> now I'd like to check them all for the existence of certain default
> keys; ie, if the dicts don't contain the keys, add them in with
> default values.
> 
> so, I've got:
> 
> for a in ['dictFoo','dictBar','dictFrotz']:
>     if hasattr(a,'srcdir') == False:
>         a['srcdir']='/usr/src'

There are a few ways to do it.

for a in ['dictFoo','dictBar','dictFrotz']:
     if not a.has_key('srcdir'):
         a['srcdir'] = '/usr/src'

for a in ['dictFoo','dictBar','dictFrotz']:
     if not 'srcdir' in a:
         a['srcdir'] = '/usr/src'

for a in ['dictFoo','dictBar','dictFrotz']:
     a.setdefault('srcdir') = '/usr/src'


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science




More information about the Python-list mailing list