Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sorted function doesn't do anything

I have a dictionary that looks like a = {'10': 2.0, '3': 2.0, '7': 1.0, '6': 1.0}

I use:

it = iter(sorted(nums.items()))

try:
    while(True):
        print it.next()

except StopIteration:
    print "\n\n"

To print the elements ordered by key value but it doesn't work. I get

('10', 1.0)
('3', 1.6666666666666667)
('6', 1.0)
('7', 1.0)

which is not what I want. I also tried bunch of other stuff but those don't work as well.. any ideas ?

like image 981
Cemre Mengü Avatar asked Mar 04 '26 20:03

Cemre Mengü


1 Answers

That is sorting the keys by their values as strings (that is, alphabetically- "1" comes before "3" comes before "6"...) rather than their integer value. If you want to sort the keys by their numerical value, you could do

iter(sorted(nums.items(), key=lambda x: int(x[0])))
like image 187
David Robinson Avatar answered Mar 07 '26 09:03

David Robinson



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!