0

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

  • first sort dictionary at Level1 by keys at Level1
  • sort dictionary at by keys at Level2

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': []}}

1 Answer 1

2
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': []}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.