expanding a variable to a dict

Arnaud Delobelle arnodel at googlemail.com
Thu Apr 3 18:12:01 EDT 2008


On Apr 3, 10:56 pm, idle <spiro.har... at gmail.com> wrote:
> I've got a variable in a loop that I'm trying to expand/translate/
> readdress as an existing dict so as to add some keys into it..
>
> eg; I have a set of existing dicts: dictFoo, dictBar, dictFrotz (names
> changed to protect the innocent)
>
> 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'
>
> the error I get (which I expect) is 'str' object doesn't support item
> assignment.
>
> what incantation do I cast on 'a' to make the interpreter parse it as
> 'dictFoo' on the first iteration, 'dictBar' on the second, and so
> forth?
>
> and/or less importantly, what is such a transformation called, to help
> me target my searching?
>
> thanks

You want a to iterate through the dictionary *objects*, not *names*,
so write

for a in [dictFoo, dictBar, dictFrotz]:
    ...

BTW, hasattr() is not what you want as it check the existence of an
attribute, i.e. a.hasattr('x') means that a.x exists; you could write
the whole thing as:

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

Or more concisely:

for a in ... :
    a.setdefault('srcdir', '/usr/src')


For more information, help(dict) is your friend :)

HTH

--
Arnaud




More information about the Python-list mailing list