Python String template dict KeyError, how to set default value

2k Views Asked by At

I want try:

"%(name)s, %(age)s" % {"name":'Bob'}`

and console Bob, 20 or Bob,.

But, this'll raise:

Traceback (most recent call last):`
  File "<pyshell#4>", line 1, in <module>`
    "%(name)s, %(age)s" % {"name":'a'}`
KeyError: 'age'`

How do I set default value? In fact, I want get Bob, when I input "%(name)s, %(age)s" % {"name":'Bob'} don't raise Except.

3

There are 3 best solutions below

5
On BEST ANSWER

You can subclass dict this way:

class Default(dict):
    def __init__(self, default, *args, **kwargs):
        self.default = default
        dict.__init__(self, *args, **kwargs)
    def __missing__(self, key):
        return self.default

# Usage:

print "%(name)s, %(age)s" % Default('', {"name":'Bob'})
print "%(name)s, %(age)s" % Default('', name='Bob')

Both of lines above prints Bob,

See it working online
See version of this code written in Python 3 working online

Edit

I reinvited collections.defaultdict.

from collections import defaultdict

print "%(name)s, %(age)s" % defaultdict(lambda: '', {"name":'Bob'})
print "%(name)s, %(age)s" % defaultdict(lambda: '', name='Bob')

See it working online

3
On

You have used ages as the key while the key variable is age. Thus you have to write it as

"%(name)s, hello. %(age)s" % {"name":'a', "age":"15"}

This will print

'a, hello. 15'
6
On

"%(name)s, %(age)s" % {"name":'Bob'} you didn't define any 'age' key in your dictionary.

In [10]: _dict = {"name":'Bob', 'age': 20}

In [11]: "%(name)s, %(age)s" %_dict

or it's always better to use string formatting. see the documentation and it is more pythonic.

In [5]: "{name}s, {age}s".format(name='Bob', age=20)
Out[5]: 'Bobs, 20s'

by jamylak suggestion,

In [17]: "{name}s, {age}s".format(**_dict)
Out[17]: 'Bobs, 20s'