Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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
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
You can’t perform that action at this time.