Python 3.6+ formatting strings from unpacking dictionaries with missing keys

若如初见. 提交于 2020-01-04 12:43:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!