| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
from __future__ import absolute_import, unicode_literals |
| 4 |
|
| 5 |
import six |
| 6 |
from copy import deepcopy |
| 7 |
|
| 8 |
|
| 9 |
def merge_dict(a, b): |
| 10 |
""" |
| 11 |
Recursively merges and returns dict a with dict b. |
| 12 |
Any list values will be combined and returned sorted. |
| 13 |
|
| 14 |
:param a: dictionary object |
| 15 |
:param b: dictionary object |
| 16 |
:return: merged dictionary object |
| 17 |
""" |
| 18 |
|
| 19 |
if not isinstance(b, dict): |
| 20 |
return b |
| 21 |
|
| 22 |
result = deepcopy(a) |
| 23 |
for key, val in six.iteritems(b): |
| 24 |
if key in result and isinstance(result[key], dict): |
| 25 |
result[key] = merge_dict(result[key], val) |
| 26 |
elif key in result and isinstance(result[key], list): |
| 27 |
result[key] = sorted(list(set(val) | set(result[key]))) |
| 28 |
else: |
| 29 |
result[key] = deepcopy(val) |
| 30 |
|
| 31 |
return result |