Skip to main content
 首页 » 编程设计

Python String template dict KeyError,如何设置默认值

2025年05月04日8wuhuacong

我想试试:

"%(name)s, %(age)s" % {"name":'Bob'}` 

和控制台 Bob, 20 或 Bob,。

但是,这会引发:

Traceback (most recent call last):` 
  File "<pyshell#4>", line 1, in <module>` 
    "%(name)s, %(age)s" % {"name":'a'}` 
KeyError: 'age'` 

如何设置默认值? 事实上,当我输入 "%(name)s, %(age)s"% {"name":'Bob'} 时,我想得到 Bob, don' t 提高 Except.

请您参考如下方法:

你可以这样继承 dict:

class Default(dict): 
    def __init__(self, default, *args, **kwargs): 
        self.default = default 
        dict.__init__(self, *args, **kwargs) 
    def __missing__(self, key): 
        return self.default 

#用法:

print "%(name)s, %(age)s" % Default('', {"name":'Bob'}) 
print "%(name)s, %(age)s" % Default('', name='Bob') 

上面两行打印Bob,

See it working online
See version of this code written in Python 3 working online

编辑

我重新邀请了collections.defaultdict .

from collections import defaultdict 
 
print "%(name)s, %(age)s" % defaultdict(lambda: '', {"name":'Bob'}) 
print "%(name)s, %(age)s" % defaultdict(lambda: '', name='Bob') 

See it working online