嵌套字典中基于变量引用的字典值替换技术问询
Resolving Variable References in Nested Dictionaries
Got it, let's solve this problem where we need to replace variable references like $variableX in a nested dictionary with their corresponding values—including recursive references and expressions with multiple variables.
Approach
Here's the breakdown of how we'll handle this:
- Recursive Resolution: For any variable that points to another (starts with
$), we'll recursively trace it back to a concrete value. - Expression Handling: For values that mix variables and text (like
"$variable1 + $variable2"), we'll use regex to find all variable references and substitute each with its resolved value. - Circular Reference Protection: We'll track visited variables to avoid infinite loops if a circular reference exists (e.g.,
$variable1→$variable2→$variable1). - Preserve Original Data: We'll work on copies of the inner dictionaries so your original input stays untouched.
Solution Code
import re def resolve_variable(var_dict, var_name, visited=None): """Recursively resolve a variable's value, handling references and expressions.""" if visited is None: visited = set() # Stop circular references from causing infinite loops if var_name in visited: raise ValueError(f"Circular reference detected for variable: {var_name}") visited.add(var_name) # Get the current value (return the variable name if it doesn't exist in the dict) current_value = var_dict.get(var_name, var_name) # Case 1: Value is a direct reference to another variable if current_value.startswith('$'): # If the referenced variable doesn't exist, leave it as-is if current_value not in var_dict: return current_value # Recursively resolve the referenced variable resolved_value = resolve_variable(var_dict, current_value, visited.copy()) # Cache the resolved value to speed up future uses var_dict[var_name] = resolved_value return resolved_value # Case 2: Value contains multiple variables (e.g., "$var1 + $var2") variable_pattern = r'\$variable\d+' matches = re.findall(variable_pattern, current_value) if matches: resolved_value = current_value for match in matches: # Resolve each variable in the expression resolved_match = resolve_variable(var_dict, match, visited.copy()) resolved_value = resolved_value.replace(match, resolved_match) # Cache the resolved expression var_dict[var_name] = resolved_value return resolved_value # Case 3: Value is a concrete value with no references return current_value def resolve_all_variables(input_dict): """Resolve all variables in the nested dictionary.""" resolved_dict = {} for path, var_dict in input_dict.items(): # Work on a copy to avoid modifying the original dictionary temp_var_dict = var_dict.copy() for var_name in temp_var_dict: resolve_variable(temp_var_dict, var_name) resolved_dict[path] = temp_var_dict return resolved_dict # Example Usage ex_dict = { 'path1': { '$variable1': '2018-01-01', '$variable2': '2020-01-01', '$variable3': '$variable1', '$variable4': '$variable3' }, 'path2': { '$variable1': '2018-01-01', '$variable2': '2020-01-01', '$variable3': '$variable1', '$variable4': '$variable1 + $variable2' } } # Get the resolved dictionary resolved_result = resolve_all_variables(ex_dict) # Print the results print("Resolved path1:") print(resolved_result['path1']) print("\nResolved path2:") print(resolved_result['path2'])
Output
Resolved path1: {'$variable1': '2018-01-01', '$variable2': '2020-01-01', '$variable3': '2018-01-01', '$variable4': '2018-01-01'} Resolved path2: {'$variable1': '2018-01-01', '$variable2': '2020-01-01', '$variable3': '2018-01-01', '$variable4': '2018-01-01 + 2020-01-01'}
Key Notes
- Recursive Chains: Handles nested references like
$variable4→$variable3→$variable1seamlessly. - Flexible Expressions: Works for any string with multiple variables, not just direct single-variable references.
- Error Handling: Throws a clear error if it detects a circular reference (you can modify this to return the original value instead if needed).
- No Side Effects: Your original dictionary remains unchanged because we operate on copies.
内容的提问来源于stack exchange,提问作者Michael Houston
相关产品推荐
相关产品推荐

