Last active
January 8, 2024 22:07
-
-
Save gyli/f60f0374defc383aa098d44cfbd318eb to your computer and use it in GitHub Desktop.
Sort Nested Dictionary By Key in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.