How to modify float value in python dictionary?
Question:
The python service gets the data in the following json format:
{
"total" : 3,
"records" : [
{
"regdId" : "A-10",
"firstName" : "Adam",
"amt" : 20
},
{
"regdId" : "A-11",
"firstName" : "Beth",
"amt" : 22
},
{
"regdId" : "A-12",
"firstName" : "Candy",
"amt" : 20.92
}
]
}
Within python, the logic is like:
a = json.loads(file.text)
print(a)
This prints:
{ "total" : 2, "records" : [ { "regdId" : "A-10", "firstName" :
"Adam", "amt" : 20 }, { "regdId" : "A-11", "firstName" : "Beth",
"amt" : 22 }, { "regdId" : "A-12", "firstName" : "Candy", "amt" :
20.92 } }
The value of "amt" gets printed as it is. Need a logic to include in the python code, so that, the value of "amt" gets formatted to 2 digits after a decimal point? 2 trailing 0s for example.
Requirement is that, the value should have 2 0s after decimal point. In cases where there are 2 digits after decimal, they should be as they are.
With a simple variable, this can be done by:
a = 12
format(a,'.2f')
How to implement the above in a dictionary?
Answers:
for index in range(len(data['records'])):
data['records'][index]['amt'] = format(data['records'][index]['amt'],'.2f')
data here is above json
The python service gets the data in the following json format:
{
"total" : 3,
"records" : [
{
"regdId" : "A-10",
"firstName" : "Adam",
"amt" : 20
},
{
"regdId" : "A-11",
"firstName" : "Beth",
"amt" : 22
},
{
"regdId" : "A-12",
"firstName" : "Candy",
"amt" : 20.92
}
]
}
Within python, the logic is like:
a = json.loads(file.text)
print(a)
This prints:
{ "total" : 2, "records" : [ { "regdId" : "A-10", "firstName" :
"Adam", "amt" : 20 }, { "regdId" : "A-11", "firstName" : "Beth",
"amt" : 22 }, { "regdId" : "A-12", "firstName" : "Candy", "amt" :
20.92 } }
The value of "amt" gets printed as it is. Need a logic to include in the python code, so that, the value of "amt" gets formatted to 2 digits after a decimal point? 2 trailing 0s for example.
Requirement is that, the value should have 2 0s after decimal point. In cases where there are 2 digits after decimal, they should be as they are.
With a simple variable, this can be done by:
a = 12
format(a,'.2f')
How to implement the above in a dictionary?
for index in range(len(data['records'])):
data['records'][index]['amt'] = format(data['records'][index]['amt'],'.2f')
data here is above json