Sort Dictionary based on the last element of Keys

I tried to sort dictionary keys by the last alphabet but it was unsuccesful

from collections import OrderedDict
dict = {'500r': '10', '600t': '9',
        '400y': '15', '200p': '2', '4500a': '32'}
dict1 = OrderedDict(sorted(dict.items(), key=lambda x: list(x[-1]) ))
print(dict1)

the output i got :
OrderedDict([(‘500r’, ’10’), (‘400y’, ’15’), (‘200p’, ‘2’), (‘4500a’, ’32’), (‘600t’, ‘9’)])

Desired output:
OrderedDict([(‘4500a’, ’32’),(‘200p’, ‘2’), (‘500r’, ’10’),(‘600t’, ‘9’), (‘400y’, ’15’)])

What am i doing wrong ?

>Solution :

I guess this is what you want to do:

from collections import OrderedDict
dict = {'500r': '10', '600t': '9',
        '400y': '15', '200p': '2', '4500a': '32'}
dict1 = OrderedDict(sorted(dict.items(), key=lambda x: x[0][-1]))
print(dict1)

Since your key is actually a tuple, x[-1] would access the last element of the tuple instead of the last element of the first element of the tuple

Leave a Reply