Python:使用 locals() 打印字典值

标签 python dictionary string-formatting syntactic-sugar

Python 中最好的工具之一是字符串格式化中的 locals():

>>> st="asdasd"
>>> print "%(st)s" % locals()
asdasd

但是,这不能用字典值来完成:

>>> d={1:2, 3:4}
>>> print "%(d[1])s" % locals()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'd[1]'

知道如何让它发挥作用吗?

最佳答案

>>> d={1:2, 3:4}
>>> print '{0[1]}'.format(d)
2
>>> print '{0[d][1]}'.format(locals())
2
>>> print '{[d][1]}'.format(locals())
2
>>>

最后一个只适用于 2.7

关于Python:使用 locals() 打印字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5004314/

相关文章:

c - 在格式化输出函数中使用 $

python - 使用 Python 的 str.format() 方法使用十六进制、八进制或二进制整数作为参数索引时出现 KeyError

python - 使用 Tornado 显示 Bokeh 生成的文件

python - 导入 python 模块而不实际执行它

java - 如何在 Java 中将 Map 转换为 List?

python - 比较 pandas 映射和合并

c# - Serilog - 缺少参数的警告

python - 无法在林间空地生成 GtkBuilder.xml

具有代理支持的 python webkit

hibernate - 使用 @ElementCollection 和 java.util.Map 的 ManyToMany(带有附加列)?