Guest User

Untitled

a guest
Jan 16th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.59 KB | None | 0 0
  1. # In CPython implementation of Python 3.6, dictionary keeps the insertion order.
  2. # As of Python 3.7, this will become the language feature.
  3. # In order to sort a dictionary including nested dictionary inside, we do:
  4.  
  5. test_dict = {'a': 1, 'c': 3, 'b': {'b2': 2, 'b1': 1}}
  6.  
  7. def sort_dict(item):
  8. if isinstance(item, dict):
  9. item = {k: v for k, v in sorted(item.items())}
  10. for k, v in item.items():
  11. if isinstance(v, dict):
  12. item[k] = sort_dict(v)
  13. return item
  14.  
  15. sorted_dict = sort_dict(test_dict)
  16.  
  17. print(sorted_dict)
  18. # {'a': 1, 'b': {'b1': 1, 'b2': 2}, 'c': 3}
Add Comment
Please, Sign In to add comment