gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:56:21 27 4
gpt4 key购买 nike

我想试试:

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

和控制台 Bob, 20Bob,

但是,这会引发:

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

关于Python String template dict KeyError,如何设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27561759/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com