anxiousPI
anxiousPI

Reputation: 203

formatting json.dump floats from dictionary in Python

I have the following dictionary in Python:

dict_a = {"a": 3.55555, "b": 6.66666, "c": "foo"}

I would like to output it to a .json file with rounding up the floats up to 2 decimals:

with open('dict_a.txt', 'w') as json_file:
   json.dump(dict_a , json_file)

output:

{"a": 3.55, "b": 6.66, "c": "foo"}

Is that possible using python 3.8 ?

Upvotes: 3

Views: 2810

Answers (2)

Zaid Al Shattle
Zaid Al Shattle

Reputation: 1534

A way to do this is by creating a new dictionary with the rounded values, you can do that in one line using dictionary comprehention while checking for non-float values as such:

Y = {k:(round(v,2) if isinstance(v,float) else v) for (k,v) in X.items()}

and then dump it. However a small note, do avoid using the word "dict" as your dictionary name, as its also a keyword in python (e.g. X = dict() is a method to create a new dictionary X). And its generally good practice to avoid those reserved keynames.

I do believe the above could could probably be optimised further (e.g, perhaps there is a function to either return the value for the round, or return a default value similar to the dictionary function get(), however I do not have any ideas on top of my mind.

Upvotes: 3

Eran Moshe
Eran Moshe

Reputation: 3208

Well, Don't use var name dict as it's a safe word in python. use dct instead.

You can loop over your keys, vals and round them them to 2nd floating point. Full working example:

dct = {"a": 3.55555, "b": 6.66666}

for k, v in dct.items():
    if type(v) is float:
       dct[k] = round(v, 2)

with open('dict.txt', 'w') as json_file:
   json.dump(dict, json_file)

Upvotes: 2

Related Questions