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%')]
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%')]
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.
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