Python 3.6+使用缺少键解压缩字典中的字符串格式 [英] Python 3.6+ formatting strings from unpacking dictionaries with missing keys
本文介绍了Python 3.6+使用缺少键解压缩字典中的字符串格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python3.4中,您可以执行以下操作:
In Python3.4 you could do the following thing:
class MyDict(dict):
def __missing__(self, key):
return "{%s}" % key
d = MyDict()
d['first_name'] = 'Richard'
print('I am {first_name} {last_name}'.format(**d))
打印,如预期的那样:
I am Richard {last_name}
但是此代码段在Python3.6 +中不起作用,尝试获取<$ c $时返回 KeyError
字典中的c> last_name 值,是否有任何变通办法可以使该字符串格式以与Python3.4中相同的方式工作?
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?
谢谢!
推荐答案
我使用 format_map
而不是 format
,跟着我例如:
I solved it using format_map
instead of format
, following my example:
print('I am {first_name} {last_name}'.format_map(d))
已打印
I am Richard {last_name}
如预期的那样。
这篇关于Python 3.6+使用缺少键解压缩字典中的字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文