Skip to content
Advertisement

How to sort a dictionary in asc or desc with negative and positive keys?

I’m trying to sort a python dictionary with negative and positives as keys.

Ex:

{
  "-25": 0,
  "-24": 0,
  "-26": 1,
  "-23": 1,
  "-3": 1,
  "-2": 1,
  "-4": 3,
  "-9": 4,
  "-6": 6,
  "-10": 7,
  "-22": 8,
  "-7": 9,
  "-5": 9,
  "-19": 10,
  "-8": 11,
  "0": 4,
  "-16": 16,
  "-14": 16,
  "-12": 16,
  "-21": 17,
  "-15": 17,
  "1": 4
  "-11": 17,
  "-20": 19,
  "-13": 20,
  "-18": 24,
  "-17": 26
}

and the expected output would be

{
  "-26": 1,      
  "-25": 0,
  "-24": 0,
  "-23": 1,
  "-22": 8,
  "-21": 17,
  "-20": 19,
  "-19": 10,
  "-18": 24,
  "-17": 26
  "-16": 16,
  "-15": 17,
  "-14": 16,
  "-13": 20,
  "-12": 16,
  "-11": 17,
  "-10": 7,
  "-9": 4,
  "-8": 11,
  "-7": 9,
  "-6": 6,
  "-5": 9,
  "-4": 3,
  "-3": 1,
  "-2": 1,
  "0": 4,
  "1": 4
}

I have tried sorting with the following code. But it is not able to sort properly as the keys are strings and it is not able to sort in the way I wanted.

dict(sorted(dict_to_sort.items(), key=lambda item: item[1])) 

Any help would be appreciated. Thanks in advance.

Advertisement

Answer

sort as int.

dict(sorted(d.items(), key=lambda x:int(x[0])))
{'-26': 1,
 '-25': 0,
 '-24': 0,
 '-23': 1,
 '-22': 8,
 '-21': 17,
 '-20': 19,
 '-19': 10,
 '-18': 24,
 '-17': 26,
 '-16': 16,
 '-15': 17,
 '-14': 16,
 '-13': 20,
 '-12': 16,
 '-11': 17,
 '-10': 7,
 '-9': 4,
 '-8': 11,
 '-7': 9,
 '-6': 6,
 '-5': 9,
 '-4': 3,
 '-3': 1,
 '-2': 1,
 '0': 4,
 '1': 4}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement