String format with optional key value

Is it possible to format a string using dict, but not necessarily without key errors?

This works great:

opening_line = '%(greetings)s %(name)s !!!' opening_line % {'greetings': 'hello', 'name': 'john'} 

But let me say that I do not know the name, and I would like to format the above strings only for 'greetings' . Sort of,

  opening_line % {'greetings': 'hello'} 

The output would be accurate even if:

 'hii %(name)s !!!' # keeping name un-formatted 

But this gives a KeyError when unpacking

Is there any way?

+6
source share
3 answers

Use defaultdict , this will allow you to specify a default value for keys that are not in the dictionary. For instance:

 >>> from collections import defaultdict >>> d = defaultdict(lambda: 'UNKNOWN') >>> d.update({'greetings': 'hello'}) >>> '%(greetings)s %(name)s !!!' % d 'hello UNKNOWN !!!' >>> 
+10
source

Some alternate with 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 

Perhaps even more succinctly, use the dictionary to set the default for each parameter,

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

For the record:

 info = { 'greetings':'DEFAULT', 'name':'DEFAULT', } opening_line = '{greetings} {name} !!!' info['greetings'] = 'Hii' print opening_line.format(**info) # Hii DEFAULT !!! 
+1
source

All Articles