3

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 ?

1
  • Some of the answers to this question will likely help you. Commented Jul 20, 2021 at 12:37

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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
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)

3 Comments

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.
Ok so you can add a little if statement, i will update the answer
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.