datopy.modeling.compare_dict_keys#

compare_dict_keys(
dict1: dict[object, object] | object,
dict2: dict[object, object] | object,
) dict[object, object] | str | None[source]#

Compare two dictionaries recursively and identify missing keys.

Parameters:
  • dict1 (dict) – The reference dictionary.

  • dict2 (dict) – The comparison dictionary to be checked against dict1.

Returns:

The nested dictionary of fields missing from dict2 relative to dict1.

Return type:

dict | list[str] | None

Examples

Setup

>>> from datopy.modeling import compare_dict_keys
>>> import copy
>>> dict1 = {'a1': 1, 'a2': 'two', 'a3': [3],
...          'b1': {'b11': 1, 'b12': 'two', 'b13': [3]},
...          'c1': {'c11': {'c111': 1, 'c112': 'two', 'c113': [3]}}
... }
>>> from datopy.modeling import compare_dict_keys

Identical dictionaries

>>> dict2 = copy.deepcopy(dict1)
>>> compare_dict_keys(dict1, dict2)

Missing nesting level 0 key

>>> del dict2['a1']
>>> compare_dict_keys(dict1, dict2)
{'missing_keys': ['a1']}

Missing nesting level 1 key

>>> dict2 = copy.deepcopy(dict1)
>>> del dict2['b1']['b12']
>>> compare_dict_keys(dict1, dict2)
{'nested_diff': {'b1': {'missing_keys': ['b12']}}}

Missing nesting level 2 key

>>> dict2 = copy.deepcopy(dict1)
>>> del dict2['c1']['c11']['c113']
>>> compare_dict_keys(dict1, dict2)
{'nested_diff': {'c1': {'nested_diff': {'c11': {'missing_keys': ['c113']}}}}}