I know that it’s possible to do the following
d = {}
d['foo'] = 'bar'
print("foo: {d[foo]}".format(**vars()))
foo: bar
But I’m having trouble accomplishing the following
d = {}
key = 'foo'
d[key] = 'bar'
print("{key}: {d[key]}".format(**vars()))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'key'
I’m expecting the output “foo: bar”
Is there a way to do this?
Look at Joran’s answer, and the comment to it from DSM: you can apply basic hacks to get a not very robust system. If you want to do this sort of thing robustly, you need to use a templating system that was designed to handle it.
Jinja 2 is one such (jinja.pocoo.org/). Google reveals many more: https://www.google.com/search?q=python+templating