问题
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!
回答1:
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.
回答2:
With Python 3.6+, you can use formatted string literals (PEP 498):
class MyDict(dict):
def __missing__(self, key):
return f'{{{key}}}'
d = MyDict()
d['first_name'] = 'Richard'
print(f"I am {d['first_name']} {d['last_name']}")
# I am Richard {last_name}
来源:https://stackoverflow.com/questions/53670748/python-3-6-formatting-strings-from-unpacking-dictionaries-with-missing-keys