Guest User

Untitled

a guest
Feb 24th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. def flatten_dictionary(dictionary):
  2. return flat(dictionary)
  3.  
  4. def flat(dictionary):
  5. if len(dictionary) == 0:
  6. return {}
  7. results = {}
  8. for key, value in iter(dictionary.items()):
  9. if type(value) is dict:
  10. sub_dict = flat(value)
  11. for k, v in iter(sub_dict.items()):
  12. if len(key) == 0:
  13. results[k] = v
  14. elif len(k) == 0:
  15. results[key] = v
  16. else:
  17. results[key + "." + k] = v
  18. else:
  19. results[key] = value
  20. return results
  21.  
  22. # each key i check if the value is string or integer
  23. # each nested value
  24. dictionary = {
  25. "Key1" : "1",
  26. "Key2" : {
  27. "a" : "2",
  28. "b" : "3",
  29. "c" : {
  30. "d" : "3",
  31. "e" : "1"
  32. }
  33. }
  34. }
  35.  
  36. print(flatten_dictionary(dictionary))
Add Comment
Please, Sign In to add comment