Newbie Variable Substitution Question

Conrad Krieg ckrieg at shaw.ca
Wed Aug 20 18:45:13 EDT 2003


>     ckrieg> for c in range(1, 3):
>     ckrieg>     print "%(c)s %(1)s" % (locals(), dict01)
>     
>     ckrieg> Results in an error: TypeError: format requires a mapping
> 
>     ckrieg> Why doesn't the second loop work?  It seems to be a 
> cleaner way
>     ckrieg> of doing this.  Am I missing something?
> 
> The right-hand argument to the % operator is a tuple of 
> dictionaries, not a
> dictionary.
> 
> Try something like this instead:
> 
>     class MultiDict(dict):
>         def __init__(self, *args):
>             self._dicts = args
> 
>         def __getitem__(self, key):
>             for d in self._dicts:
>                 try:
>                     return d[key]
>                 except KeyError:
>                     pass
>             raise KeyError, key
> 
>         def has_key(self, key):
>             for d in self._dicts:
>                 if key in d:
>                     return True
>             return False
> 
>     dict01 = { '1': 'a', '2': 'b' }
>     for c in range(1, 3):
>         print "%(c)s %(1)s" % MultiDict(locals(), dict01)

Thanks!  This worked great!

Conrad





More information about the Python-list mailing list