[Tutor] preventing KeyError from "%"
Michael P. Reilly
arcege@speakeasy.net
Thu, 3 May 2001 12:08:18 -0400 (EDT)
Lance E Sloan 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:
>
> ^IKeyError: 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:
>
> ^Ilance = {'first': 'Lance', 'mi': 'E', 'last': 'Sloan'}
> ^Imonty = {'first': 'Monty', 'last': 'Python'}
>
> ^Iprint '%(first)s %(mi)s %(last)s\n' % lance
> ^Iprint '%(first)s %(mi)s %(last)s\n' % monty
>
> it would produce:
>
> ^ILance E Sloan
> ^IMonty Python
>
> instead of throwing an exception for the "% monty" line.
Sorry, but no. All values must exist in the dictionary.
>From the Python Library Reference Manual:
If the right argument is a dictionary (or any kind of mapping), then
the formats in the string _must_ have a parenthesized key into that
dictionary inserted immediately after the "%" character, and each
format formats the corresponding entry from the mapping.
<URL: http://www.python.org/doc/current/lib/typesseq-strings.html>
You could make sure that all values are an empty string at first.
Create a dictionary with empty strings first, and populate it with
the values afterward. Or go thru the dictionary and find the missing
fields and populate the dictionary that way.
-Arcege
--
+----------------------------------+-----------------------------------+
| Michael P. Reilly | arcege@speakeasy.net |