in tensorflow_model_optimization/python/core/internal/tensor_encoding/utils/py_utils.py [0:0]
def merge_dicts(dict1, dict2):
"""Merges dictionaries of corresponding structure.
The inputs must be dictionaries, which have the same key only if the
corresponding values are also dictionaries, which will be processed
recursively.
This method is mainly to be used together with the `split_dict_py_tf` method.
Args:
dict1: An arbitrary `dict`.
dict2: A `dict`. A key is in both `dict1` and `dict2` iff both of the
corresponding values are also `dict` objects.
Returns:
A `dict` with values merged from the input dictionaries.
Raises:
TypeError:
If either of the input arguments is not a dictionary.
ValueError:
If the input dictionaries do not have corresponding structure.
"""
merged_dict = collections.OrderedDict()
if not (isinstance(dict1, dict) and isinstance(dict2, dict)):
raise TypeError
for k, v in six.iteritems(dict1):
if isinstance(v, dict):
if not (k in dict2 and isinstance(dict2[k], dict)):
raise ValueError('Dictionaries must have the same structure.')
merged_dict[k] = merge_dicts(v, dict2[k])
else:
merged_dict[k] = v
for k, v in six.iteritems(dict2):
if isinstance(v, dict):
if not (k in dict1 and isinstance(dict1[k], dict)):
# This should have been merged in previous loop.
raise ValueError('Dictionaries must have the same structure.')
else:
if k in merged_dict:
raise ValueError('Dictionaries cannot contain the same key, unless the '
'corresponding values are dictionaries.')
merged_dict[k] = v
return merged_dict