python字典能否只替换它找到的东西?

python字典能否只替换它找到的东西?,python,dictionary,Python,Dictionary,以下工作很好: line = "Hello %(firstname)s %(lastname)s, how are you?" print line % dict (firstname = "Mike", lastname="Kane") 和打印: 你好,迈克·凯恩,你好吗 但是,如果我没有lastname的值,我仍然希望它能够工作: line = "Hello %(firstname)s %(lastname)s, how are you?" print line % dict (first

以下工作很好:

line = "Hello %(firstname)s %(lastname)s, how are you?"
print line % dict (firstname = "Mike", lastname="Kane")
和打印:

你好,迈克·凯恩,你好吗

但是,如果我没有
lastname
的值,我仍然希望它能够工作:

line = "Hello %(firstname)s %(lastname)s, how are you?"
print line % dict (firstname = "Mike")
我希望它忽略lastname键并打印:

你好,迈克,你好吗


您可以使用
defaultdict

from collections import defaultdict

line = "Hello %(firstname)s %(lastname)s, how are you?"
print line % defaultdict(str, firstname = "Mike")

说明:
defaultdict
初始值设定项的第一个参数必须是返回默认值的可调用参数
str
是可调用的,返回空字符串(请尝试
str()
)。

您可以使用生成字典的子类,为缺少的值提供默认值:

>>> class Dict(dict):
        def __missing__(self, key):
            # supply a default value for a given key
            return key


>>> d = Dict(firstname = 'Mike')
>>> print "Hello %(firstname)s %(lastname)s, how are you?" % d
Hello Mike lastname, how are you?
这些技术使您能够完全控制返回的内容。以下是一些变体:

return '--missing--'       returns a default string
return key.upper()         highlight the missing key
return ''                  return an empty string
印刷品

Hello Mike , how are you?

这不是一种灵活的技术,因为工厂函数不接受参数。如果改用_umissing _uu,可以返回的内容有很多选项。@RaymondHettinger:是的,但OP的规范中没有。
Hello Mike , how are you?