You can use a recursive function for this: First, check whether the type of the template and the original are the same. If so, you have to do different things for different types. E.g., for lists, you could reduce the original list to the length of the template list, and for dictionaries preserve only the keys from the template. In both cases, remember to recursively call the trim
function again for the elements contained in those lists or dictionaries.
def trim(template, original):
if type(template) != type(original):
raise Exception("Types don't match")
if isinstance(template, dict):
# iterate keys and apply trim to values from orig dictionary
return {k: trim(v, original[k]) for k, v in template.items()}
elif isinstance(template, list):
# zip lists and apply trim to pairs of templ and orig elements
return [trim(t, o) for t, o in zip(template, original)]
else:
# atom: just return the original value
return original
Example (note that I also changed the value of "c"
to a list):
>>> A = { "a" : { "b": 3, "c": [4,5] } }
>>> B = { "a" : { "b": 7, "c": [8,9,10], "d": "howdy" } }
>>> trim(A, B)
{'a': {'b': 7, 'c': [8, 9]}}