I'm using Google's PageSpeed Insights API in Python, and I've come across a baffling issue. The API presents me with a format string and arguments to that format string, and I need to figure out how to actually format the string. The problem is that the arguments are given in a really odd fashion.
This is how the arguments to the format string are presented to me (I'm showing it as an assignment to make it clearer):
args = [
{
'type': 'INT_LITERAL',
'value': '21',
'key': 'NUM_SCRIPTS'
},
{
'type': 'INT_LITERAL',
'value': '20',
'key': 'NUM_CSS'
}
]
And this is a sample format string, also given to me by the API:
format = 'Your page has {{NUM_SCRIPTS}} blocking script resources and {{NUM_CSS}} blocking CSS resources. This causes a delay in rendering your page.'
I know that sometimes people like to avoid answering the question asked and instead offer an answer that is tailored to their beliefs about coding 'right' and 'wrong,' so to reiterate, I am given both the arguments and the format string by the API. I am not creating them myself, so I can't do this in a more straightforward fashion.
What I need to know is how to extract the key field of the dicts in the args list so that I can use them with "".format
in a way that will let me pass the value field to the named arguments.
I apologize if this is somehow super obvious; I'm fairly new to Python and I don't know a lot about the little details. I did do my due diligence and search for an answer before asking, but I didn't find anything and it's not an easily searchable problem.
EDIT:
I thought maybe this 'list of dicts' thing was commonplace with Google's APIs or something, that maybe there was an automatic way to associate the arguments (like string.format_map
). I ended up just doing it the simple way, without string.format
.
for x in args:
format = format.replace('{{' + x['key'] + '}}', x['value'])