具有可选dict键值的字符串格式 [英] String format with optional dict key-value
本文介绍了具有可选dict键值的字符串格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用dict格式化字符串,但是可以选择不存在键错误?
Is there any way to format string with dict but optionally without key errors?
这很好:
opening_line = '%(greetings)s %(name)s !!!'
opening_line % {'greetings': 'hello', 'name': 'john'}
但是,假设我不知道名字,我想在行上方设置格式仅用于'greetings'
.像
But let's say I don't know the name, and I would like to format above line
only for 'greetings'
. Something like,
opening_line % {'greetings': 'hello'}
即使:
'hii %(name)s !!!' # keeping name un-formatted
但这会在打开包装时显示 KeyError
But this gives KeyError
while unpacking
有什么办法吗?
推荐答案
使用 defaultdict ,这将允许您为字典中不存在的键指定默认值.例如:
Use defaultdict, this will allow you to specify a default value for keys which don't exist in the dictionary. For example:
>>> from collections import defaultdict
>>> d = defaultdict(lambda: 'UNKNOWN')
>>> d.update({'greetings': 'hello'})
>>> '%(greetings)s %(name)s !!!' % d
'hello UNKNOWN !!!'
>>>
这篇关于具有可选dict键值的字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文