Reputation: 453
I have a dictionary where the values are floating point numbers. I am trying to sort the dictionary in decreasing order of values and I am trying to break ties by sorting the keys in ascending order.
I implemented the following code to achieve this:
for key, value in sorted(dictionary.items(), key=lambda x: (-x[1], x[0])):
print key, value
Some of my values seem out of place.
2315 0.000232471518033
2823 0.000232414850716
3649 0.00023239634392
3695 0.00023239634392
3883 0.00023239634392
3479 0.00023239634392
3562 0.00023239634392
3613 0.00023239634392
As per the above code line starting with 3479 should be printed before the line starting with 3649.
Any ideas on what might be wrong with the way I have sorted the dictionary? Has it got anything to do with the precision of floating point numbers?
Upvotes: 1
Views: 114
Reputation: 87
I think you are ordering with respect to the wrong components of the dictionary. You can just do:
for key, value in sorted(dictionary.items(), key=lambda x: (x[0]):
print key, value
if you want to order per key, and
for key, value in sorted(dictionary.items(), key=lambda x: (-x[1]):
print key, value
if you want to order per value.
Upvotes: 0
Reputation: 799450
Has it got anything to do with the precision of floating point numbers?
Yes.
>>> 0.0002323963439201
0.0002323963439201
>>> print 0.0002323963439201
0.00023239634392
Upvotes: 7