I’m trying to sort a python dictionary with negative and positives as keys.
Ex:
JavaScript
x
30
30
1
{
2
"-25": 0,
3
"-24": 0,
4
"-26": 1,
5
"-23": 1,
6
"-3": 1,
7
"-2": 1,
8
"-4": 3,
9
"-9": 4,
10
"-6": 6,
11
"-10": 7,
12
"-22": 8,
13
"-7": 9,
14
"-5": 9,
15
"-19": 10,
16
"-8": 11,
17
"0": 4,
18
"-16": 16,
19
"-14": 16,
20
"-12": 16,
21
"-21": 17,
22
"-15": 17,
23
"1": 4
24
"-11": 17,
25
"-20": 19,
26
"-13": 20,
27
"-18": 24,
28
"-17": 26
29
}
30
and the expected output would be
JavaScript
1
30
30
1
{
2
"-26": 1,
3
"-25": 0,
4
"-24": 0,
5
"-23": 1,
6
"-22": 8,
7
"-21": 17,
8
"-20": 19,
9
"-19": 10,
10
"-18": 24,
11
"-17": 26
12
"-16": 16,
13
"-15": 17,
14
"-14": 16,
15
"-13": 20,
16
"-12": 16,
17
"-11": 17,
18
"-10": 7,
19
"-9": 4,
20
"-8": 11,
21
"-7": 9,
22
"-6": 6,
23
"-5": 9,
24
"-4": 3,
25
"-3": 1,
26
"-2": 1,
27
"0": 4,
28
"1": 4
29
}
30
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.
JavaScript
1
2
1
dict(sorted(dict_to_sort.items(), key=lambda item: item[1]))
2
Any help would be appreciated. Thanks in advance.
Advertisement
Answer
sort as int
.
JavaScript
1
2
1
dict(sorted(d.items(), key=lambda x:int(x[0])))
2
JavaScript
1
28
28
1
{'-26': 1,
2
'-25': 0,
3
'-24': 0,
4
'-23': 1,
5
'-22': 8,
6
'-21': 17,
7
'-20': 19,
8
'-19': 10,
9
'-18': 24,
10
'-17': 26,
11
'-16': 16,
12
'-15': 17,
13
'-14': 16,
14
'-13': 20,
15
'-12': 16,
16
'-11': 17,
17
'-10': 7,
18
'-9': 4,
19
'-8': 11,
20
'-7': 9,
21
'-6': 6,
22
'-5': 9,
23
'-4': 3,
24
'-3': 1,
25
'-2': 1,
26
'0': 4,
27
'1': 4}
28