I'm trying to use pythons str.format(dict) to replace some named arguments in str - but not all. I want to replace the remaining named arguments at a later point in my code:
strDict = {'title':'This is the title.', 'msg':'This is the message'}
str2 = '{title}\n{msg}\n{furtherMsg}'.format(**strDict)
strDict2 = {'furtherMsg':'some more text'}
outStr = str2.format(**strDict2)
However, I get a KeyError: 'furtherMsg in the line str2=... Is there a way to only replace some of the named arguments in a string with str.format()?
I know, that in the simple example above I could just use format with the combined dictionary at the end but that's not an option in my original problem.
I'm using Python 2.7.
EDIT:
I tried the solution from the question suggested by martijn-pieters but it doesn't work:
class D(dict):
def __missing__(self, k):
return '{'+k+'}'
strDict = D({'title':'This is the title', 'msg':'This is the message.'})
str2 = '{title}\n{msg}\n{furtherMsg}'.format(**strDict)
still gives me a KeyError: 'furtherMsg', while
strDict['furtherMsg']
returns
'furtherMsg'
I also tried with
class D(dict):
def __missing__(self, k):
return '{{'+k+'}}'
but that doesn't work, either.