2

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 ?

anxiousPI
  • 183
  • 1
  • 12

2 Answers2

3

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.

Zaid Al Shattle
  • 1,454
  • 1
  • 12
  • 21
  • Thanks for sharing this, i updated the post to change the variable name and include a string in the dictionary. As this works using a comprehension for a dict with values as floats, it does not work if other data types are present. – anxiousPI Jul 20 '21 at 12:49
  • All good. I can think of an improvement when I am home to allow comprehension to be used. Meanwhile, Erans answer should hopefully be sufficient – Zaid Al Shattle Jul 20 '21 at 15:40
2

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)
Eran Moshe
  • 3,062
  • 2
  • 22
  • 41
  • As I mentioned in the previous comment, I have updated the variable name of the dictionary and its contents. This does not work if the contents contain other data types. – anxiousPI Jul 20 '21 at 12:52
  • 1
    Ok so you can add a little if statement, i will update the answer – Eran Moshe Jul 20 '21 at 13:35
  • I think it's a good solution, unless a JSON encoder was used. I tried checking that with a statement that checks if a string was there, but it did not work for me. – anxiousPI Jul 20 '21 at 19:37