开发者

Python: Using locals() to print dictionary value

One of the nicest tools in Python is locals() in string formatting:

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

However, this can't be done with dictionary values:

>>> d={1:2, 3:4}
>>> print "%(d[1])s" % locals()
Traceback (most recent call last):
  File "<std开发者_如何学Pythonin>", line 1, in <module>
KeyError: 'd[1]'

Any idea how to make this work?


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

the last one only works with 2.7

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜