Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to format floating-point numbers in a dictionary to remove trailing and leading zeros in Python?

I have a dictionary in Python with floating-point values like this:

{'0': 0.773, '1': -0.529, '2': -0.004, '3': -0.035}

I want to format the values in the dictionary to remove unnecessary trailing zeros and leading zeros before the decimal point. For example, I want the output to be:

{'0':.773,'1':-.529,'2':-.004,'3':-.035}

How can i do it with re (or any way else)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want to save the data in a text file and i want to save as much space as possible.

Thanks!

>Solution :

Modern Python won’t stringify floats with extra trailing zeroes (the only trailing zero it will ever include is the single 0 after the decimal point for whole numbers), so that problem is already handled.

To get from the natural repr of a dict of this form to the form you said you wanted, just perform a couple replacements:

s = {'0': 0.773, '1': -0.529, '2': -0.004, '3': -0.035}
print(repr(s).replace('0.','.').replace(': ', ':'))

which outputs:

{'0':.773, '1':-.529, '2':-.004, '3':-.035}

If the floats might be outside the range -1.0 to 1.0, you’ll need a slight tweak so 10.0 won’t become 1.0:

print(repr(s).replace(' 0.','.').replace('-0.','-.').replace(': ', ':'))

This obviously won’t work properly for a dict with arbitrary data (e.g. if it has string keys or values that happen to contain 0. or : ), but for the example, it works just fine, no regex required.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading