Search code examples
pythondictionaryreverse

Reverse Order of a Nested Dictionary Python


I have a two-layered dictionary and would like a simple command or function (if possible) to reverse the order of the dictionary, but only the outer layer, not the inner. For instance, if my dictionary were as follows:

{'dictA': {'key_1': 'value_1'}, 'dictB': {'key_2': 'value_2'}, 'dictC': {'key_3', 'value_3'}}

and I wanted to instead make it the following:

{'dictC': {'key_3', 'value_3'}, 'dictB': {'key_2': 'value_2'}, 'dictA': {'key_1': 'value_1'}}

How would I do this? I have tried methods like invertdict() and inv_map = {v: k for k, v in my_map.items()}, but I had no success with either.

Any help is appreciated!


Solution

  • Reverse the items:

    >>> dict(reversed(d.items()))
    {'dictC': {'value_3', 'key_3'}, 'dictB': {'key_2': 'value_2'}, 'dictA': {'key_1': 'value_1'}}