如何从DeepDiff对比结果构建指定结构的Python字典?
To solve this problem, we need to transform the path strings from DeepDiff's dictionary_item_added set into a nested Python dictionary that mirrors the structure of the added items in the second JSON file. Here's a step-by-step approach:
Step 1: Parse Path Strings into Key Lists
First, we'll convert each path string (like root['spark']['toll']) into a list of nested keys (like ['spark', 'toll']). This lets us traverse the second JSON file to retrieve the corresponding values.
Step 2: Retrieve Values from the Source JSON
Using the parsed key lists, we'll extract the values of the added items from the second JSON file.
Step 3: Build the Target Nested Dictionary
We'll construct the final dictionary by iterating over each key list and creating the nested structure needed to place each value in the correct position.
Complete Code Implementation
def parse_path(path): """Convert a DeepDiff path string to a list of nested keys.""" # Remove the 'root' prefix and split into individual key parts key_parts = path.replace("root", "").strip("[]").split("']['") # Strip quotes from each key and return the list return [part.strip("'") for part in key_parts] def get_nested_value(data, keys): """Retrieve a value from a nested dictionary using a list of keys.""" current_level = data for key in keys: current_level = current_level[key] return current_level def build_target_dict(deepdiff_result, source_json): """Build the target dictionary from DeepDiff results and the source JSON.""" target_dict = {} # Iterate over each added item path in the DeepDiff result for path in deepdiff_result.get('dictionary_item_added', set()): keys = parse_path(path) value = get_nested_value(source_json, keys) # Traverse or create the nested structure in the target dict current_dict = target_dict for idx, key in enumerate(keys): if idx == len(keys) - 1: # Last key: assign the value current_dict[key] = value else: # Create nested dict if it doesn't exist if key not in current_dict: current_dict[key] = {} current_dict = current_dict[key] return target_dict # Example usage json1 = {"spark": {"ttl":3, "poll":34}} json2 = {"spark": {"ttl":3, "poll":34, "toll":23}, "cion": 34} deepdiffresult = {'dictionary_item_added': {"root['spark']['toll']", "root['cion']"}} expecteddict = build_target_dict(deepdiffresult, json2) print(expecteddict) # Output: {'spark': {'toll': 23}, 'cion': 34}
Key Notes
- Path Parsing: The
parse_pathfunction handles the conversion of DeepDiff's path format into a usable list of keys. It removes therootprefix and splits the string at each']['separator. - Nested Value Retrieval:
get_nested_valuesafely traverses the source JSON to get the value associated with each key list. - Dict Construction:
build_target_dictdynamically creates the nested structure in the target dictionary, ensuring each value is placed in the correct nested position.
This solution works for any depth of nested keys and will correctly handle all items listed in dictionary_item_added.
内容的提问来源于stack exchange,提问作者Srivignesh

