如何在python中使用str.format()和字典?

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()不接受单个字典,而是接受关键字参数.

  • 原因是"我在{0 [place]}上有一个{0 [fruit]}.".format(dic)`也适用 - `dic`是这里的第0个位置参数,你可以访问它的键模板. (3认同)
  • @bogdan,`**`表示字典应该扩展为关键字参数列表.`format`方法不将字典作为参数,但它确实采用关键字参数. (2认同)

jfs*_*jfs 8

自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)