Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.)

like image 854
mart1n Avatar asked Nov 06 '17 13:11

mart1n


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.

like image 121
cs95 Avatar answered Nov 14 '22 23:11

cs95


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

>>> a = {'test1.1': 5}
>>> 'test: %(test1.1)s' % a
'test: 5'
like image 40
wim Avatar answered Nov 15 '22 00:11

wim