expanding a variable to a dict

Max M maxm at mxm.dk
Thu Apr 3 18:44:56 EDT 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