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