开发者

Python: Using locals() to print dictionary value

开发者 https://www.devze.com 2023-02-10 08:54 出处:网络
One of the nicest tools in Python is locals() in string formatting: >>> st=\"asdasd\" >>> print \"%(st)s\" % locals()

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

精彩评论

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