Reputation: 590
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!
Upvotes: 2
Views: 722
Reputation: 590
I solved it using format_map
instead of format
, following my example:
print('I am {first_name} {last_name}'.format_map(d))
Printed
I am Richard {last_name}
As expected.
Upvotes: 3