Skip to content

Instantly share code, notes, and snippets.

@gyli
Last active January 8, 2024 22:07
Show Gist options
  • Save gyli/f60f0374defc383aa098d44cfbd318eb to your computer and use it in GitHub Desktop.
Save gyli/f60f0374defc383aa098d44cfbd318eb to your computer and use it in GitHub Desktop.
Sort Nested Dictionary By Key in Python
# In CPython implementation of Python 3.6, dictionary keeps the insertion order.
# From Python 3.7, this will become a language feature.
# In order to sort a dictionary by key including nested dictionary inside, we can do:
def sort_dict(item: dict):
"""
Sort nested dict
Example:
Input: {'a': 1, 'c': 3, 'b': {'b2': 2, 'b1': 1}}
Output: {'a': 1, 'b': {'b1': 1, 'b2': 2}, 'c': 3}
"""
return {k: sort_dict(v) if isinstance(v, dict) else v for k, v in sorted(item.items())}
# This function only handles nested dict, you may add list sorting if you want to sort a nested JSON recursively
@solaarTW
Copy link

solaarTW commented Nov 7, 2022

That is beautiful, nicely done. I added to it alittle so that it would also sort lists. I wish there was a way to include a sorting feature inside the return statement instead of having to brutalize your code.

def sort_dict(item: dict):
    for k, v in sorted(item.items()):
        item[k] = sorted(v) if isinstance(v, list) else v
    return {k: sort_dict(v) if isinstance(v, dict) else v for k, v in sorted(item.items())}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment