I'm new to Python and I'm currently working on solving problems to improve my coding skills. I'm working on a question where I need to stable sort
a dictionary in python. Please find the details below:
Input:
1 2
16 3
11 2
20 3
3 5
26 4
7 1
22 4
The above input, I have added into two lists k and v
:
k = ['1', '16', '11', '20', '3', '26', '7', '22']
v = ['2', '3', '2', '3', '5', '4', '1', '4']
I have added both the lists into a dictionary to have it as a key-value pair. I have used OrderDict
because I want to have the elements in the same order as they are in the input.
from collections import OrderedDict
d = OrderedDict(zip(k, v))
Now, I need to sort the dictionary d
in the reverse order with respect to values. (I actually have to do a stable sort and since sorted
in python is a stable sort, I have used that. Source: Here) For that:
s = sorted(d, key = itemgetter(1), reverse=True)
Expected Output:
3 5
26 4
22 4
16 3
20 3
1 2
11 2
7 1
But after I implemented the above sorted
function, I'm not able to get the expected output. I get IndexError: string index out of range
Can someone tell me where am I doing wrong. Is my approach wrong or flow is wrong? Could you please tell me why I'm not able to get the output as expected. Thanks in advance. Any help would be much appreciated.