Sort Dictionary based on the last element of Keys

Question:

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 ?

Asked By: Kuhan Vickneswaran

||

Answers:

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.

Answered By: fsimonjetz

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

Answered By: W00dy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.