[Tutor] preventing KeyError from "%"
Remco Gerlich
scarblac@pino.selwerd.nl
Thu, 3 May 2001 17:53:11 +0200
On 0, Lance E Sloan <lsloan@umich.edu> wrote:
> I use the "%" operator with strings a lot. One of the things I
> commonly do is set a dictionary from values submitted via a web page
> form or read from a database. It's not uncommon that some fields may
> be empty and there wouldn't be a key for that field in the dictionary.
> When I use that dictionary with "%" and the format string calls for
> that key, I get this exception:
>
> KeyError: x
>
> How can I get "%" to not throw an exception, but instead skip over that
> key and move on to the next substitution? For example, if I have
> this:
>
> lance = {'first': 'Lance', 'mi': 'E', 'last': 'Sloan'}
> monty = {'first': 'Monty', 'last': 'Python'}
>
> print '%(first)s %(mi)s %(last)s\n' % lance
> print '%(first)s %(mi)s %(last)s\n' % monty
>
> it would produce:
>
> Lance E Sloan
> Monty Python
>
> instead of throwing an exception for the "% monty" line.
You can't do that with the standard dictionary, so you have to roll your
own, inherited from UserDict, i.e.:
from UserDict import UserDict
class MyDict(UserDict):
def __getitem__(self, arg):
# Returns "" for any arg that's not in the underlying dictionary
if self.data.has_key(arg):
return self.data[arg]
else:
return ""
print '%(first)s %(mi)s %(last)s\n' % MyDict(lance)
--
Remco Gerlich