I have a dictionary containing some floating-point values.
When I print the dictionary as is, I get these values printed in full accuracy.
However, when I attempt to print each value separately, I get them truncated.
A simple coding example to illustrate the problem:
d = {'x': 0.010000000000000231}
print d # outputs {'x': 0.010000000000000231}
print d['x'] # outputs 0.01
Now, of course I can solve this using format
, i.e., in the example above:
print '{:.18f}'.format(d['x']) # outputs 0.010000000000000231
However, I wish to avoid this kind of solution.
First and foremost, because I do not know the exact precision required for each entry in the dictionary. Second, because I prefer to avoid the type of cumbersome coding, which involves specifying print format of every field to begin with.
In other words, I want to do something like:
print 'x = {}'.format(d['x'])
Or:
print 'x =',d['x']
And get the value of d['x']
printed in its full precision.
Why does the Python interpreter chooses different print formats for d
and for d['x']
, and what approach can I take here in order to achieve my purpose?
Python's dict. values() method can be used to retrieve the dictionary values, which can then be printed using the print() function.
keys() method can be used to retrieve the dictionary keys, which can then be printed using the print() function. A view object that shows a list of every key in the dictionary is the result of the dict. keys() method. The dictionary's elements can be accessed using the dict.
Dictionaries and lists can be converted to the string with str() . In this case, they are converted to a one-line string without newline, as in the output of print() . You can use pprint. pformat() to get the output of pprint.
Truncation is the act or process of truncating—shortening something by removing part of it. It can also mean the state of having been truncated. Truncation can involve the removal of the beginning of something, the end of it, the top of it, or another part of it.
What you're seeing is a difference between what is printed when the __str__
method is invoked vs when the __repr__
is invoked.
An example:
In [816]: print 0.010000000000000231
0.01
In [817]: print repr(0.010000000000000231)
0.010000000000000231
The reason for this difference is because str
attempts to truncate the number in python2.
This is changed in python3, and the str
and repr
behave consistently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With