Guest User

Untitled

a guest
Jun 19th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. from itertools import product
  2.  
  3. d1 = dict(zip(product('AB', [0, 1]), range(2*2)))
  4. d2 = dict(zip(product('AB', [0, 1], [True, False]), range(2*2*2)))
  5. d3 = dict(zip(product('CD', [0, 1], [True, False], 'AB'), range(2*2*2*2)))
  6.  
  7. # For d1
  8. {'A': {0: 0, 1: 1}, 'B': {0: 2, 1: 3}}
  9.  
  10. # For d2
  11. {'A': {0: {True: 0, False: 1}, 1: {True: 2, False: 3}},
  12. 'B': {0: {True: 4, False: 5}, 1: {True: 6, False: 7}}}
  13.  
  14. # Beginning of result for d3
  15. {
  16. 'C': {
  17. 0: {
  18. True: {
  19. 'A': 0
  20. 'B': 1
  21. },
  22. False: {
  23. 'A': 2,
  24. 'B': 3
  25. },
  26. 1: # ...
  27.  
  28. from collections import defaultdict
  29.  
  30. def nested_dict():
  31. return defaultdict(nested_dict)
  32.  
  33. def nest(d: dict) -> dict:
  34. res = nested_dict()
  35. for (i, j, k), v in d.items():
  36. res[i][j][k] = v
  37. return res
  38.  
  39. def set_arbitrary_nest(keys, value):
  40. """
  41. >>> keys = 1, 2, 3
  42. >>> value = 5
  43. result --> {1: {2: {3: 5}}}
  44. """
  45.  
  46. res = {}
  47. it = iter(keys)
  48. last = next(it)
  49. res[last] = {}
  50. lvl = res
  51. while True:
  52. try:
  53. k = next(it)
  54. lvl = lvl[last]
  55. lvl[k] = {}
  56. last = k
  57. except StopIteration:
  58. lvl[k] = value
  59. return res
  60.  
  61. >>> set_arbitrary_nest([1, 2, 3], 5)
  62. {1: {2: {3: 5}}}
Add Comment
Please, Sign In to add comment