Recursively update the content in `src_dict` into `tgt_dict`. For example, tgt_dict = { 'a': 1, 'b': {'c': 2}, 'd': 3, } src_dict = { 'a': 4, 'b': {'e': 5}, 'f': 6, } After the function tgt_dict will contain: tgt_dict
(
tgt_dict: T.MutableMapping[T.Any, T.Any],
src_dict: T.MutableMapping[T.Any, T.Any],
)
| 193 | |
| 194 | |
| 195 | def recursive_dict_update( |
| 196 | tgt_dict: T.MutableMapping[T.Any, T.Any], |
| 197 | src_dict: T.MutableMapping[T.Any, T.Any], |
| 198 | ): |
| 199 | """ |
| 200 | Recursively update the content in `src_dict` into `tgt_dict`. |
| 201 | |
| 202 | For example, |
| 203 | tgt_dict = { |
| 204 | 'a': 1, |
| 205 | 'b': {'c': 2}, |
| 206 | 'd': 3, |
| 207 | } |
| 208 | src_dict = { |
| 209 | 'a': 4, |
| 210 | 'b': {'e': 5}, |
| 211 | 'f': 6, |
| 212 | } |
| 213 | |
| 214 | After the function tgt_dict will contain: |
| 215 | tgt_dict = { |
| 216 | 'a': 4, |
| 217 | 'b': {'c': 2, 'e': 5}, |
| 218 | 'd': 3, |
| 219 | 'f': 6, |
| 220 | } |
| 221 | Notice that the function does not replace tgt_dict['b'] with the new |
| 222 | dictionary, but update it. |
| 223 | |
| 224 | Args: |
| 225 | tgt_dict: |
| 226 | dictionary to be updated |
| 227 | src_dict: |
| 228 | dictionary containing the source content |
| 229 | """ |
| 230 | |
| 231 | if src_dict is None: |
| 232 | return |
| 233 | |
| 234 | for key, val in src_dict.items(): |
| 235 | if key not in tgt_dict or tgt_dict[key] is None or isinstance(tgt_dict[key], HyperParams.TBD): |
| 236 | tgt_dict[key] = val |
| 237 | else: |
| 238 | if isinstance(val, (dict, HyperParams)): |
| 239 | assert isinstance(tgt_dict[key], (dict, HyperParams)), f"{key}, {type(tgt_dict[key])}" |
| 240 | recursive_dict_update(tgt_dict[key], src_dict[key]) |
| 241 | else: |
| 242 | tgt_dict[key] = val |