设置默认值
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
或使用默认字典(这样你就不需要输入所有默认值,它们会神奇地变成'')
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
或者正如 abarnert 指出的那样,您可以将其简化为
from collections import defaultdict
my_dict = defaultdict(str,form)
msg = """<html><p>%(Frist_Name)s</p><p>%(Last_Name)s</p></html> """ % my_dict
这是我刚刚在终端中完成的完整示例
>>> 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