Advertisement
Guest User

Untitled

a guest
Dec 8th, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. def merge(dict1, dict2, func=None):
  2. """
  3. update dict1 with key/value pairs in dict2. If they have keys in common,
  4. merge the respective values.
  5.  
  6. :param dict1: dict to be updated
  7. :param dict2: dict to add to dict1
  8. :param func: function taking two values and returning a new value.
  9. :return: None. merge is done in-place.
  10.  
  11. >>> d1 = {'roberto': 28, 'chris': 12, 'evan': 121}
  12. >>> d2 = {'roberto': 3, 'chris': 25, 'epifanio': 350}
  13. >>> from operator import add
  14. >>> merge(d1, d2, add)
  15. >>> d1
  16. {'chris': 37, 'evan': 121, 'roberto': 31, 'epifanio': 350}
  17. """
  18. if func is None:
  19. dict1.update(dict2)
  20. else:
  21. for k in dict2:
  22. if k in dict1:
  23. dict1[k] = func(dict1[k], dict2[k])
  24. else:
  25. dict1[k] = dict2[k]
  26.  
  27.  
  28. def merged(dict1, dict2, func=None):
  29. """
  30. Merge two dicts as in merge, and return the merged dict. Does not
  31. mutate the original dicts.
  32. :param dict1: dict
  33. :param dict2: dict
  34. :param func: merge function that takes two arguments and returns a value
  35. :return: merged dict
  36.  
  37. >>> d1 = {'robert': 28, 'chrisse': 12, 'evan': 121}
  38. >>> d2 = {'robert': 3, 'chrisse': 25, 'epifanio': 350}
  39. >>> from operator import add
  40. >>> merged(d1, d2, add)
  41. {'robert': 31, 'evan': 121, 'chrisse': 37, 'epifanio': 350}
  42. """
  43. d = dict1.copy()
  44. if func is None:
  45. d.update(dict2)
  46. else:
  47. for k in dict2:
  48. if k in d:
  49. d[k] = func(d[k], dict2[k])
  50. else:
  51. d[k] = dict2[k]
  52. return d
  53.  
  54. if __name__ == '__main__':
  55. import doctest
  56. doctest.testmod()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement