[Tutor] preventing KeyError from "%"
Benoit Dupire
bdupire@seatech.fau.edu
Thu, 03 May 2001 12:00:26 -0400
if don't know if it's what you are looking for, but the following wouldn't
do what you want ?
monty = {'first': 'Monty', 'last': 'Python'}
for key in ['first', 'mi', 'last']"
if not lance.has_key(key):
monty[key]=''
print '%(first)s %(mi)s %(last)s\n' % monty
It just add the keys that don't exist...
Benoit
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:
>
> 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.
>
> --
> Lance E Sloan
> Web Services, Univ. of Michigan: Full-service Web and database design,
> development, and hosting. Specializing in Perl & Python CGIs.
> http://websvcs.itd.umich.edu/ - "Putting U on the Web"
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
--
Benoit Dupire
Graduate Student
----------------
I'd like to buy a new Boomerang. How can i get rid of the old one?