Advertisement
Guest User

Untitled

a guest
Sep 18th, 2019
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. def flatten_dictionnary(d, new_dic, key=""):
  2. for k, v in d.items():
  3. if type(v) is dict:
  4. if not key:
  5. key = k
  6. else:
  7. key += k
  8. flatten_dictionnary(d[k], new_dic, key + '_' )
  9. key = ""
  10. elif type(v) is list:
  11. for i, e in enumerate(v):
  12. new_dic[key + k + "_" + str(i)] = e
  13. else:
  14. if key:
  15. new_dic[key + k] = v
  16. else:
  17. new_dic[k] = v
  18.  
  19. return new_dic
  20.  
  21.  
  22. if __name__ == "__main__":
  23. d = {
  24. "a": 1,
  25. "c": {"a": 2},
  26. "b": {"t": 5, "y": 10, 'f':{'a':1}},
  27. "e": [1, 2],
  28. "z": {"k": 2, "xx": [3, 4]},
  29. "w": {"a": {"c": [5, 6], "d": 4}},
  30. }
  31. new_dic = flatten_dictionnary(d, {}, "")
  32. print("New dic:", new_dic)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement