0

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.

mozway
  • 194,879
  • 13
  • 39
  • 75

1 Answers1

1

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()}
mozway
  • 194,879
  • 13
  • 39
  • 75
  • Shouldn't this be using an `OrderedDict` or the like to guarantee that insertion order is remembered no matter the Python implementation? – Luatic Mar 22 '22 at 09:40
  • 1
    @LMD dictionaries are maintaining insertion order since python 3.7 ([part of spec](https://mail.python.org/pipermail/python-dev/2017-December/151283.html), not implementation detail) ;) – mozway Mar 22 '22 at 09:42