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.
Here is one way to do it:
>>> sorted_kv = sorted(d.items(), key=lambda (k,v):int(v), reverse=True)
>>> OrderedDict(sorted_kv)
OrderedDict([('3', '5'), ('26', '4'), ('22', '4'), ('16', '3'), ...
This takes the key/value pairs from the dictionary, sorts them, and creates a new ordered dictionary with the required ordering.
The key= argument to sorted() specifies that the pairs are to be sorted according to the numeric value of the second item.
The reason I needed to call int() is that your dictionary keeps both the keys and the values as strings. Sorting them as-is will work, but will produce the lexicographic ordering instead of the numeric one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With