Python: Using locals() to print dictionary value

6.1k Views Asked by At

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 "<stdin>", line 1, in <module>
KeyError: 'd[1]'

Any idea how to make this work?

1

There are 1 best solutions below

0
On BEST ANSWER
>>> 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