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 do i sort nested dictionary based on value of first key

I have a dictionary in following format:

{
 'Item1': {'Cl': ['E1', 'E2', 'E3'], 'Re': ['E1', 'E2', 'E3']}, 
 'Item2': {'Cl': ['E1', 'E2', 'E3'], 'Re': ['E1', 'E2', 'E3']}, 
 'Item3': {'Cl': ['E1', 'E2', 'E3'], 'Re': ['E1', 'E2', 'E3']},
 'Item4': {'Cl': ['E2', 'E1', 'E3'], 'Re': ['E1', 'E2', 'E3']}
 }

And i want to restructure in the following format:

{
 'Item1': {'Re': ['E1', 'E2', 'E3'], 'Cl': ['E1', 'E2', 'E3']}, 
 'Item2': {'Re': ['E1', 'E2', 'E3'], 'Cl': ['E1', 'E2', 'E3']}, 
 'Item3': {'Re': ['E1', 'E2', 'E3'], 'Cl': ['E1', 'E2', 'E3']},
 'Item4': {'Re': ['E2', 'E1', 'E3'], 'Cl': ['E1', 'E2', 'E3']}
     }

I have tried sorted() but it doesn’t seem to work or maybe i’m not implementing it in the correct way.

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 :

You can use a dictionary comprehension. I am assuming here that you want to sort the keys by reverse lexicographic order:

{k:{k2:v[k2] for k2 in sorted(v, reverse=True)} for k,v in d.items()}

output:

{'Item1': {'Re': ['E1', 'E2', 'E3'], 'Cl': ['E1', 'E2', 'E3']},
 'Item2': {'Re': ['E1', 'E2', 'E3'], 'Cl': ['E1', 'E2', 'E3']},
 'Item3': {'Re': ['E1', 'E2', 'E3'], 'Cl': ['E1', 'E2', 'E3']},
 'Item4': {'Re': ['E1', 'E2', 'E3'], 'Cl': ['E2', 'E1', 'E3']}}

If you want to push ‘Re’ to the beginning, and keep the rest in the same order (assuming more than 2 keys), you could do:

{k:{k2:v[k2] for k2 in sorted(v, key='Re'.__ne__)} for k,v in d.items()}
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