Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # In CPython implementation of Python 3.6, dictionary keeps the insertion order.
- # As of Python 3.7, this will become the language feature.
- # In order to sort a dictionary including nested dictionary inside, we do:
- test_dict = {'a': 1, 'c': 3, 'b': {'b2': 2, 'b1': 1}}
- def sort_dict(item):
- if isinstance(item, dict):
- item = {k: v for k, v in sorted(item.items())}
- for k, v in item.items():
- if isinstance(v, dict):
- item[k] = sort_dict(v)
- return item
- sorted_dict = sort_dict(test_dict)
- print(sorted_dict)
- # {'a': 1, 'b': {'b1': 1, 'b2': 2}, 'c': 3}
Add Comment
Please, Sign In to add comment