1

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.

Thomas
  • 1,277
  • 1
  • 12
  • 20
  • The reason that this doesn't work is that the `**` unpacking of the dictionary creates a regular `dict`, so the `__missing__` functionality is lost. – kindall Dec 19 '14 at 17:04
  • It works with `%` string interpolation, though. – kindall Dec 19 '14 at 17:09
  • @kindall: I still don't get it. In the quoted question they use `my_string.format(**D(name='minerz029'))`. Isn't that the same thing? And is there anything I can do to prevent loosing the `__missing__` functionality? – Thomas Dec 19 '14 at 17:13
  • Yes, it's the same thing. As noted, it works in Python 3 but not Python 2.x. – kindall Dec 19 '14 at 17:15
  • Right, I missed that part. Thought it was only about the format_map. Using `str2 = '%(title)s\n%(msg)\n%(furtherMsg)'%strDict` - as you suggested - works, however. Thanks! – Thomas Dec 19 '14 at 17:22
  • @Thomas, it's "losing" not "loosing" - it may help to remember that you write "loser" not "looser" – NeilG Jul 10 '19 at 05:53

0 Answers0