Home > front end >  How do i sort nested dictionary based on value of first key
How do i sort nested dictionary based on value of first key

Time:03-22

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.

CodePudding user response:

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()}
  • Related