Kuhan Vickneswaran
Kuhan Vickneswaran

Reputation: 11

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 ?

Upvotes: 0

Views: 225

Answers (2)

W00dy
W00dy

Reputation: 51

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

Upvotes: 1

fsimonjetz
fsimonjetz

Reputation: 5802

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.

Upvotes: 1

Related Questions