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

Ada*_*tan 4 python dictionary string-formatting syntactic-sugar

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

>>> st="asdasd"
>>> print "%(st)s" % locals()
asdasd
Run Code Online (Sandbox Code Playgroud)

但是,使用字典值无法做到这一点:

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

知道如何使这项工作?

Mar*_*ani 6

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

最后一个只适用于2.7