Python 多级字典的字符串格式化

标签 python string-formatting

从模板字符串呈现值的常见技术如下所示:

>>> num = 7
>>> template = 'there were {num} dwarves'
>>> print template.format(**locals())
there were 7 dwarves

此方法适用于具有 __str__ 方法的任何数据类型,例如听写:

>>> data = dict(name='Bob', age=43)
>>> template = 'goofy example 1 {data}'
>>> print template.format(**locals())
goofy example 1 {'age': 43, 'name': 'Bob'}

但是,当 key 引用字典项时,它不起作用:

>>> template = 'goofy example 2 {data["name"]}'
>>> print template.format(**locals())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: '"name"'

在格式字符串之外的代码中有效的标识符在格式字符串内使用时无效,这很不方便,而且看起来很奇怪。我错过了什么吗?有办法做到这一点吗?

我希望能够引用嵌套字典结构中几层的元素,例如 somedict['level1key']['level2key']['level3key']。到目前为止,我唯一可行的方法是将这些值复制到标量变量中以进行字符串格式化,这很糟糕。

最佳答案

您可以通过在字符串中使用 {data[name]} 而不是 {data["name"]} 来实现。

您可以在格式字符串中指定的内容类型受到限制。不允许使用任意表达式,并且键以简化的方式解释,如 the documentation 中所述。 :

it is not possible to specify arbitrary dictionary keys (e.g., the strings '10' or ':-]') within a format string.

在这种情况下,您可以取出 key ,因为它是一个简单的字母数字字符串,但是,正如文档所建议的,您不一定总是这样做。如果您有奇怪的字典键,您可能必须更改它们以在格式字符串中使用它们,或诉诸其他方法(例如使用 + 显式连接字符串值)。

关于Python 多级字典的字符串格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22904397/

相关文章:

python - 如何使用 Keras 获得第 k 层之后的激活值?

python - python-3.6 中带有 'f' 前缀的字符串

Python 在 f.write 中使用变量

python - 使用 MatPlotLib (Python) 向我的堆叠条形图添加文本

python - 如何更改 scrapy view 命令使用的浏览器?

python - 无法使用 selenium webdriver 单击网页中的链接

python - Django Celery delay() 总是推送到默认的 'celery' 队列

Java在printf中打印双值零

formatting - 如何格式化标准 ML 打印输出?

java - 从数组打印时出现异常