Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String format with optional dict key-value

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 unpacking

Is there any way?

like image 918
Nikhil Rupanawar Avatar asked Dec 16 '13 10:12

Nikhil Rupanawar


People also ask

How do you use %s in Python?

The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value.

Can dictionary values be a string?

Dictionary values can be just about anything (int, lists, functions, strings, etc).

Can strings be dict keys?

Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key.


2 Answers

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 !!!'
>>> 
like image 132
piokuc Avatar answered Sep 26 '22 02:09

piokuc


For the record:

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

info['greetings'] = 'Hii'
print opening_line.format(**info)
# Hii DEFAULT !!!
like image 23
feqwix Avatar answered Sep 26 '22 02:09

feqwix