0
{'100': 3.2, '98': 2.8333333333333335, '101': 3.6666666666666665, '102': 3.375, '99': 2.0833333333333335, '97': 2.5, '103': 4.0, '105': 2.3333333333333335, '104': 3.0, '108': 4.0, '106': 4.0, '107': 1.0}

This is my original dictionary that intended to sort by key, here is my code.

for key in sorted(new.keys()):
out.update({key:new[key]})

But the value returned seems weird

{'100': 3.2, '101': 3.6666666666666665, '102': 3.375, '103': 4.0, '104': 3.0, '105': 2.3333333333333335, '106': 4.0, '107': 1.0, '108': 4.0, '97': 2.5, '98': 2.8333333333333335, '99': 2.0833333333333335}

I don't understand why the out dictionary output an 3 digit sorted first instead of 2 digit numbers. How can I solve this?

AlexWithYou
  • 399
  • 1
  • 4
  • 14
  • 1
    your keys are strings. strings sort lexically, not with the numerical values. either change keys to ints, or use a `key` argument where you turn the values into ints for numerical sorting – Paritosh Singh Feb 13 '20 at 19:32

1 Answers1

0

Thanks@paritosh Simply use out.update({int(key):new[key]}) solve this problem

AlexWithYou
  • 399
  • 1
  • 4
  • 14