Forcing dict keys to be used as argument specifiers with str.format

Viewed 233

I have the following string interpolation:

>>> a = {'test1.1': 5}
>>> 'test: {test1.1}'.format(**a)
KeyError: 'test1'

It obviously fails because format is literally trying to access the object test1 and its attribute 1. Is there a way to format this string and force the key values to be taken as strings? (Looking for a Python 2 and 3 solution.)

2 Answers

A little hack, but this does the trick:

In [5]: 'test: {0[test1.1]}'.format(a)
Out[5]: 'test: 5'

Use dict-like indexing with [..]. The 0 is positional indexing, and a is the 0th argument. If it's the only argument, you can omit 0.

Just another alternative. The old %-style formatting doesn't care:

>>> a = {'test1.1': 5}
>>> 'test: %(test1.1)s' % a
'test: 5'
Related