John Byro
John Byro

Reputation: 734

How to sort nested dictionaries in python

This is a most common question to be asked but with different use case

I have some dictionary structure in place as the below.

dict_1 = {
    'c': {
        'c3': [],
        'c1': [],
        'c2': []
    },
    'a': {
        'a3': [],
        'a1': [],
        'a2': []
    },
    'b': {
        'b3': [],
        'b1': [],
        'b2': []
    },
}

I want to sort it on two levels

i.e, after the sorting the output should be as

dict_1 = {
    'a': {
        'a1': [],
        'a2': [],
        'a3': []
    },
    'b': {
        'b1': [],
        'b2': [],
        'b3': []
    },
    'c': {
        'c1': [],
        'c2': [],
        'c3': []
    },
}

I am able to do it in two steps, first sorting the dictionary at Level1 by keys. Then iterating the dictionary and again sorting the dictionary at level2 by keys again.

Is their pythonic way to achieve the same in one sorting ?

I managed to sort the above as

dict_1 = {k: {k1: v1 for k1, v1 in sorted(v.items(), key=lambda level_2_dict: level_2_dict[0])}
          for k, v in sorted(dict_1.items(), key=lambda level_1_dict: level_1_dict[0])}

print(dict_1)

# output 
{'a': {'a1': [], 'a2': [], 'a3': []}, 'b': {'b1': [], 'b2': [], 'b3': []}, 'c': {'c1': [], 'c2': [], 'c3': []}}

Upvotes: 0

Views: 1487

Answers (1)

BhusalC_Bipin
BhusalC_Bipin

Reputation: 811

dict_1 = {key: dict(sorted(dict_1[key].items())) for key in sorted(dict_1)}

>>> print(dict_1)
>>> {'a': {'a1': [], 'a2': [], 'a3': []}, 'b': {'b1': [], 'b2': [], 'b3': []}, 'c': {'c1': [], 'c2': [], 'c3': []}}

Upvotes: 2

Related Questions