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 can I arrange a dictionary using python so that the values are represented from lowest to highest order?

I have the following dictionary:

d = {'A': {'A1': 2, 'A4': 4, 'A5': 1}, 'B': {'B3': 1, 'B7': 8, 'B5': 2}}

How can I rearrange the dictionary to organize the values from lowest to highest order?
I am expecting to have the following output after rearranging the dictionary based on the values:

d = {'A': {'A5': 1, 'A1': 2, 'A4': 4}, 'B': {'B3': 1, 'B5': 2, 'B7': 8,}}

I tried to use the sorted option, d = sorted(d.items()), but it sorts the dictionary based on the keys.

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

>Solution :

d = {'A': {'A1': 2, 'A4': 4, 'A5': 1}, 'B': {'B3': 1, 'B7': 8, 'B5': 2}}
sorted_dict = {i:dict(sorted(d[i].items(),key=lambda x:x[1])) for i in d.keys()}

I know that it’s pretty hard to read, so I will try to explain what I can.
Basically, you are using the sorted function which takes an iterable and a function of one argument which tells the sorted function to sort the iterable on the basis of that lambda function.

Edit:
I forgot to show the output.

{'A': {'A5': 1, 'A1': 2, 'A4': 4}, 'B': {'B3': 1, 'B5': 2, 'B7': 8}}
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