Guest User

Untitled

a guest
Jul 19th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. import collections
  4.  
  5. def quacks_like_dict(object):
  6. """Check if object is dict-like"""
  7. return isinstance(object, collections.Mapping)
  8.  
  9. def merge(a, b):
  10. """Merge two deep dicts non-destructively
  11.  
  12. Uses a stack to avoid maximum recursion depth exceptions
  13.  
  14. >>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6}
  15. >>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}}
  16. >>> c = merge(a, b)
  17. >>> from pprint import pprint; pprint(c)
  18. {'a': 1, 'b': {1: 1, 2: 7}, 'c': 3, 'd': {'z': [1, 2, 3]}}
  19. """
  20. assert quacks_like_dict(a), quacks_like_dict(b)
  21. dst = a.copy()
  22.  
  23. stack = [(dst, b)]
  24. while stack:
  25. current_dst, current_src = stack.pop()
  26. for key in current_src:
  27. if key not in current_dst:
  28. current_dst[key] = current_src[key]
  29. else:
  30. if quacks_like_dict(current_src[key]) and quacks_like_dict(current_dst[key]) :
  31. stack.append((current_dst[key], current_src[key]))
  32. else:
  33. current_dst[key] = current_src[key]
  34. return dst
  35.  
  36. if __name__ == '__main__':
  37. # Run test in timer
  38. import timeit
  39. print timeit.Timer('doctest.testmod()', 'import doctest').timeit(number=1), 'seconds'
Add Comment
Please, Sign In to add comment