Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’)])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading