How can I replace named vars in a string in python from an incomplete dictionary?

StackOverflow https://stackoverflow.com/questions/16405049

  •  14-04-2022
  •  | 
  •  

Pregunta

I have a long html form I'm retriving data from and then populating in an html document and emailing it. I'm using form = cgi.FieldStorage() to get the data posted from my form and then I have a string for the message body similer to (but mutch longer than)

 msg = """<html><p>%(Frist_Name)s</p><p>%(Last_Name)s</p></html> """ % form

Which according to debuging works until it finds one of my named vars that was not submitted with the form.

There are many optional fields on the form, what can I do to either make this work or do something similar so I don't have to gather all the fields beforehand(ie manually reenter each field) and create a blank one if it's None? Or is there no easier way then doing exactly that?

¿Fue útil?

Solución

set defaults

my_data_dict = {'first_name':'','last_name':'','blah':'','something_else':''} #defaults with all values from format string
my_data_dict.update(form) #replace any values we got
 msg = """<html><p>%(Frist_Name)s</p><p>%(Last_Name)s</p></html> """ % my_data_dict

or use default dict (this way you wont need to input all your defaults they will just magically be '')

from collections import defaultdict
my_dict = defaultdict(str)
print my_dict['some_key_that_doesnt_exist']  #should print empty string
my_dict.update(form)
msg = """<html><p>%(Frist_Name)s</p><p>%(Last_Name)s</p></html> """ % my_data_dict

or as abarnert points out you can simplify it to

from collections import defaultdict
my_dict = defaultdict(str,form)
msg = """<html><p>%(Frist_Name)s</p><p>%(Last_Name)s</p></html> """ % my_dict

here is a complete example I just did in my terminal

>>> d = defaultdict(str,{'fname':'bob','lname':'smith','zipcode':11111})
>>> format_str = "Name: %(fname)s  %(lname)s\nPhone: %(telephone)s\nZipcode: %(z
ipcode)s"
>>> d
defaultdict(<type 'str'>, {'lname': 'smith', 'zipcode': 11111, 'fname': 'bob'})
>>> #notice no telephone here
...
>>> d['extra_unneeded_argument'] =' just for show'
>>> d
defaultdict(<type 'str'>, {'lname': 'smith', 'extra_unneeded_argument': ' just f
or show', 'zipcode': 11111, 'fname': 'bob'})
>>> print format_str%d
Name: bob  smith
Phone:
Zipcode: 11111
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top