bog*_*dan 17 python dictionary
这段代码有什么问题?
dic = { 'fruit': 'apple', 'place':'table' }
test = "I have one {fruit} on the {place}.".format(dic)
print(test)
>>> KeyError: 'fruit'
Run Code Online (Sandbox Code Playgroud)
Sve*_*ach 31
应该
test = "I have one {fruit} on the {place}.".format(**dic)
Run Code Online (Sandbox Code Playgroud)
请注意**
. format()
不接受单个字典,而是接受关键字参数.
自Python 3.2以来就有''.format_map()
功能:
test = "I have one {fruit} on the {place}.".format_map(dic)
Run Code Online (Sandbox Code Playgroud)
优点是它接受任何映射,例如,具有__getitem__
动态生成值的方法的类或collections.defaultdict
允许您使用不存在的键的类.
它可以在旧版本上模拟:
from string import Formatter
test = Formatter().vformat("I have one {fruit} on the {place}.", (), dic)
Run Code Online (Sandbox Code Playgroud)