2

I have template strings with named arguments (for ex. msg = "{a} {b} {c}") and series of functions returning results of some statistical calculations in dictionaries. I want to use these dictionaries to fill templates. However, there is a problem. The exact number of the arguments in the template is not as same as in the dictionary; thus, I can not use simple msg.format(**result). Is there a way to overcome this problem, keeping unused format-blocks for further use?

This is what I have:

msg.format(a=1,b=2) -> KeyError: 'c'

This is what I want:

msg.format(a=1,b=2) -> "1 2 {c}"
pault
  • 41,343
  • 15
  • 107
  • 149
  • Possible duplicate of [python format string unused named arguments](https://stackoverflow.com/questions/17215400/python-format-string-unused-named-arguments) – pault Nov 25 '19 at 15:34
  • Actually I may have spoken too soon. There is a way to use `.format` in this matter, if you first [get the names of the args of string using `string.Formatter`](https://stackoverflow.com/a/24181068/5858851). Then you can do something like `msg.format(**{**args, **result})` where `args = {x[1]:'{'+x[1]+'}' for x in Formatter().parse(msg)}`. @Jean-François Fabre – pault Nov 25 '19 at 15:52
  • the duplicate looks OK. You may post an answer in the original q – Jean-François Fabre Nov 25 '19 at 16:00
  • 1
    @Jean-FrançoisFabre the difference here is the unpacking of the dict but I defer to your judgement. Will consider posting an answer on one of the originals. – pault Nov 25 '19 at 16:11
  • FYI: posted [this answer](https://stackoverflow.com/a/59036131/5858851) on the linked duplicate. – pault Jan 21 '20 at 16:24

0 Answers0