-2

If I have this:

>>> templ = "{aa} fd3443fds {bb} 543gfdgf {cc}"
>>> d1 = {"aa": "this is aa", "bb": "this is bb33", "cc": "this is cc5222"}

What's the easiest way to replace the values in {} in templ with the corresponding values in "d1", preferably using the function "format" of String?

Joota
  • 1

1 Answers1

1

If you have a template string templ and a dictionary d1, you can fill in the template variables thusly:

result = templ.format(**d1)

If you have an object d1 with attributes d1.aa, d1.bb, etc:

class Class1: pass
d1 = Class1()
d1.aa = d1.bb = d1.cc = 'hello'

then you could rewrite your template string:

templ = "{0.aa} fd3443fds {0.bb} 543gfdgf {0.cc}"
result = templ.format(d1)

or you may be able to use vars(d1):

templ = "{aa} fd3443fds {bb} 543gfdgf {cc}"
result = templ.format(**vars(d1))
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • how can I do that for the attributes of an instance? in other words, if d1 is an instance of some Class1 and it has attributes "aa", "bb" and "cc". Passing it as-is throws an exception. – Joota Apr 13 '16 at 16:59
  • @Joota - Try using `.format(**vars(d1))`. See my recent edit. – Robᵩ Apr 13 '16 at 17:13
  • FYI, in modern Python, `result = templ.format(**d1)` can be done with [`str.format_map`](https://docs.python.org/3/library/stdtypes.html#str.format_map) to support arbitrary non-`dict` objects as long as they support the mapping protocol by doing `result = templ.format_map(d1)`. At one point, this was also necessary for `dict` subclasses, but it looks like that's not the case in 3.5 at least (`'{a},{b}',format(**defaultdict(lambda: 'foo'))` produces `'foo,foo'` instead of erroring out, indicating the `defaultdict` status isn't lost). – ShadowRanger Apr 13 '16 at 17:20