In Python3.4 you could do the following thing:
class MyDict(dict):
def __missing__(self, key):
return "{%s}" % key
And then something like:
d = MyDict()
d['first_name'] = 'Richard'
print('I am {first_name} {last_name}'.format(**d))
Printing, as expected:
I am Richard {last_name}
But this snippet won't work in Python3.6+, returning a KeyError
while trying to get the last_name
value from the dictionary, is there any workaround for that string formatting to work in the same way as in Python3.4?
Thanks!
With Python 3.6+, you can use formatted string literals (PEP 498):
I solved it using
format_map
instead offormat
, following my example:Printed
As expected.