String format with optional dict key-value

时间秒杀一切 提交于 2019-11-29 13:56:27

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 !!!'
>>> 

Some alternates to defaultDict,

greeting_dict = {'greetings': 'hello'}

if 'name' in greeting_dict :
    opening_line = '{greetings} {name}'.format(**greeting_dict)
else:
    opening_line = '{greetings}'.format(**greeting_dict)

print opening_line

Maybe even more succinctly, use dictionary get to set per parameter defaults,

'{greetings} {name}'.format(greetings=greeting_dict.get('greetings','hi'),
                            name=greeting_dict.get('name',''))

For the record:

info = {
    'greetings':'DEFAULT',
    'name':'DEFAULT',
    }
opening_line = '{greetings} {name} !!!'

info['greetings'] = 'Hii'
print opening_line.format(**info)
# Hii DEFAULT !!!
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!