def walk_dict_and_add_if_match(d, target_key, target_value, add_object): if isinstance(d, dict): for k, v in d.items(): # If the current key is the target and the value matches, add the provided object if k == target_key and v == target_value: d.update(add_object) # Recursively walk through the nested dictionary walk_dict_and_add_if_match(v, target_key, target_value, add_object) elif isinstance(d, list): for i, item in enumerate(d): # Recursively walk through each item in the list walk_dict_and_add_if_match(item, target_key, target_value, add_object) # Example usage with a nested dictionary, a target key, and a target value: example_data = { "key1": { "subkey1": "value1", "subkey2": { "subsubkey1": "value2" }, }, "key2": ["item1", "item2", {"subkey": "value3"}], } # Define the object to be added, the target key, and the target value object_to_add = {"id": "new_value"} target_key_name = "subkey" target_value_name = "value3" # Call the function with the example data walk_dict_and_add_if_match(example_data, target_key_name, target_value_name, object_to_add) print(example_data)