0

Is there a better way of doing the following..

    template = """
This goes here {Item1},,, and here {Item2}
   and here {Item3}
"""

mydict = {'Item1':'Cat', 
          'Item2':'Dog', 
          'Item3':'Hamster', 
          'Item4':'Donkey'
         }

result = template.format(Item1=mydict['Item1'], Item2=mydict['Item2'], Item3=mydict['Item3'])

The main thing being that the place holders in the format string are named exactly the same as the key values in the dictionary.

BUT The dictionary may contain more key values than there are place holders. The place holders will ALWAYS be a subset of the dictionary

I have tried

template.format(**mydict)

but that gives a KeyError exception. I had hoped that silently catching that exception would work but it doesn't

My gut feeling is that there must be a more pythonic way to do this other than the long-hand way above.

Thanks

The Welsh Dragon
  • 519
  • 1
  • 4
  • 19
  • Possible duplicate of [How do I format a string using a dictionary in python-3.x?](https://stackoverflow.com/questions/5952344/how-do-i-format-a-string-using-a-dictionary-in-python-3-x) – Patrick Haugh Dec 17 '18 at 23:49
  • 2
    `result = template.format(**mydict)` ["`**mydict` means "treat the key-value pairs in the dictionary as additional named arguments to this function call.""](https://stackoverflow.com/a/21809162/1248974) – chickity china chinese chicken Dec 17 '18 at 23:57
  • Thank you both. If the dictionary has more keys than there are place holders in the format string, will **mydict still work? – The Welsh Dragon Dec 18 '18 at 00:13
  • @TheWelshDragon try it and see? .. just tried it myself and indeed `**mydict` will still properly fill the output if there are less placeholders than keys, the output is only the first two values: `This goes here Cat,,, and here Dog` – chickity china chinese chicken Dec 18 '18 at 00:56
  • Can you please include show us how `template.format(**mydict)` gives a KeyError exception? – chickity china chinese chicken Dec 27 '18 at 07:45

0 Answers0