Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sort() issue with negative values

Good day everyone,

I ran into a problem when sorting percentage values in my dict with the sorted() function. When i get to the negative numbers it sorts the largest negative number first followed by the second largest etc. I want the smallest negative number to appear first. Is there any way to modify my sorted() to achieve this? Cheers!

yoy_dict = sorted(yoy_dict.items(), key=lambda x: x[1], reverse = True)

yoy_dict = [('HOUGANG', '1.130759%'),

 ('JURONG EAST', '0.786807%'),

 ('PUNGGOL', '0.238738%'),

 ('SEMBAWANG', '-2.150383%'),

 ('WOODLANDS', '-2.043103%'),

 ('CHOA CHU KANG', '-1.923021%'),

 ('SENGKANG', '-1.548278%'),

 ('MARINE PARADE', '-1.445532%'),

 ('CENTRAL AREA', '-1.266556%'),

 ('JURONG WEST', '-1.037612%'),

 ('YISHUN', '-0.843832%'),

 ('BUKIT BATOK', '-0.296952%')]
like image 743
hakkonen Avatar asked Dec 16 '25 19:12

hakkonen


2 Answers

You need to convert your values to float to avoid sorting strings:

res = sorted(yoy_dict.items(), key=lambda x: float(x[1][:-1]), reverse=True)

Result:

print(res)

[('HOUGANG', '1.130759%'),
 ('JURONG EAST', '0.786807%'),
 ('PUNGGOL', '0.238738%'),
 ('BUKIT BATOK', '-0.296952%'),
 ('YISHUN', '-0.843832%'),
 ('JURONG WEST', '-1.037612%'),
 ('CENTRAL AREA', '-1.266556%'),
 ('MARINE PARADE', '-1.445532%'),
 ('SENGKANG', '-1.548278%'),
 ('CHOA CHU KANG', '-1.923021%'),
 ('WOODLANDS', '-2.043103%'),
 ('SEMBAWANG', '-2.150383%')]
like image 62
jpp Avatar answered Dec 19 '25 10:12

jpp


It seems that your problem is due to the usage of strings instead of numbers for storing percentage values. You need to convert strings to floats.

 key=lambda x: float(x[1][:-1])

Note:

10 > 9  # True
'10' > '9'  # False

It's because strings are being compared one character in time. When Python finds the first different characters in two strings, it chooses the biggest and stops here.

like image 36
Maxim Krabov Avatar answered Dec 19 '25 08:12

Maxim Krabov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!