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

How to get sorted dictionary from another one instead of a list

I have Dict ={'Deblai': [100, 1], 'Blocage': [10, 4], 'Beton de propreté': [50, 2]} dictionary and want to sort it based on the second element of the value which is a list.

I tried OrderedDict = sorted(Dict.items(), key=lambda x: x[1][1]) but it returns an ordered list instead of a dictionary.

This is what I expect :

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

OrderedDict = {('Deblai', [100, 1]), ('Beton de propreté', [50, 2]), ('Blocage', [10, 4])}

How I can get a dictionary instead of list ?

>Solution :

You can do it using dictionary comprehension like this:

unsorted_dct ={'Deblai': [100, 1], 'Blocage': [10, 4], 'Beton de propreté': [50, 2]}
sorted_dct = {k: v for k, v in sorted(unsorted_dct.items(), key=lambda item: item[1][1])}
print(sorted_dct)

output:

{'Deblai': [100, 1], 'Beton de propreté': [50, 2], 'Blocage': [10, 4]}
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