String format with optional dict key-value
12,634
Solution 1
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 !!!'
>>>
Solution 2
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',''))
Solution 3
For the record:
info = {
'greetings':'DEFAULT',
'name':'DEFAULT',
}
opening_line = '{greetings} {name} !!!'
info['greetings'] = 'Hii'
print opening_line.format(**info)
# Hii DEFAULT !!!
Author by
Nikhil Rupanawar
Software development with python and related frameworks. Server and Storage Virtualization technologies. Perspective towards Coding standards, code efficiency, code re-usability, performance improvements.
Updated on July 19, 2022Comments
-
Nikhil Rupanawar almost 2 years
Is there any way to format string with dict but optionally without key errors?
This works fine:
opening_line = '%(greetings)s %(name)s !!!' opening_line % {'greetings': 'hello', 'name': 'john'}
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'}
Output would be fine even if:
'hii %(name)s !!!' # keeping name un-formatted
But this gives
KeyError
while unpackingIs there any way?
-
Jason R. Coombs about 8 yearsI'd extract commonality in
if/else
and instead,fmt = '{greetings} {name}' if 'name' in greeting_dict else '{greetings}'; print(fmt.format(**greeting_dict))
.