Home > Blockchain >  Sort Dictionary based on the last element of Keys
Sort Dictionary based on the last element of Keys

Time:08-05

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 ?

CodePudding user response:

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

CodePudding user response:

items returns key value pairs that are passed to the lambda function. So you first need to get the first element from that tuple to get the key, then the last character from that:

dict1 = OrderedDict(sorted(dict.items(), key=lambda x: x[0][-1] ))

NB: There's no need to cast the string into a list.

  • Related