gdogg371
gdogg371

Reputation: 4142

Adding a format to an element of this code?

I have a dictionary being returned from a webpage as a .JSON() object that I am formatting using the code below:

responser = responser.json()

teamStatDicts = responser[u'teamTableStats']

for statDict in teamStatDicts:

    mylookup = ("{tournamentName},{tournamentId},{regionCode},{tournamentRegionId},{teamName},{teamId},"
    "{minsPlayed},{ranking},{rating},{apps},".decode('cp1252').format(**statDict))

This would give ma sample output of:

Premier League,2,gb-eng,252,Arsenal,13,75,1,6.22145454545,5,1.0,4.5,5.5,

In this example I would like to apply a format to the item {rating} so that it only has two decimal places. Is it possible to adapt the code above to do this?

Thanks

Upvotes: 1

Views: 20

Answers (1)

Danny Staple
Danny Staple

Reputation: 7332

Format allows specification of precision and type like this sample:

>>>"{0:.2f}".format(23.2245)
'23.22'

That would be "{rating:.2f}" in your case.

This is documented in the python docs: https://docs.python.org/2/library/string.html#format-specification-mini-language

Upvotes: 1

Related Questions