通用函数开发需求:替换字典/嵌套字典/字典列表的键值
Got it, let's solve this problem. You need a way to target a specific key and replace its value, no matter how deep it's nested in dictionaries or lists of dictionaries. Recursion is perfect here because it can handle those arbitrary nesting levels seamlessly.
Here's a robust function that does exactly what you need:
import copy def replace_key_value(data, target_key, new_value): # Make a deep copy to avoid modifying the original data (optional but recommended) data_copy = copy.deepcopy(data) if isinstance(data_copy, dict): # Iterate through each key-value pair in the dictionary for key, value in data_copy.items(): if key == target_key: # Replace the value if we match the target key data_copy[key] = new_value else: # Recursively check the value (it could be another dict or list) replace_key_value(value, target_key, new_value) elif isinstance(data_copy, list): # Iterate through each item in the list (items could be dicts/lists/other types) for item in data_copy: replace_key_value(item, target_key, new_value) return data_copy
How It Works
Let's break down the logic so you understand what's happening:
- Dictionaries: We loop through every key. If the key matches our target, we swap the value. If not, we recursively run the function on the value (since it might be a nested dictionary or list).
- Lists: We loop through each element in the list and run the function on it—this handles lists of dictionaries, lists of lists, etc.
- Other Types: Any non-dict/non-list values (like strings, numbers) are left untouched, which is exactly what we want.
Example Usage with Your Data
Let's test this with the dictionary you provided. First, define your original data:
original_data = { "environment": [ { "appliances": [ {"services-status": "GOOD", "ping-status": "REACHABLE"}, {"softwareVersion": "16.1-R1-S2 50b46b5 20170829", "services-status": "GOOD", "ping-status": "REACHABLE"} ], "vd_url": "https://bla1" }, { "appliances": [ {"ipAddress": "10.4.64.108", "type": "branch", "sync-status": "IN_SYNC"}, {"services-status": "GOOD", "ping-status": "REACHABLE", "sync-status": "IN_SYNC"} ], "vd_url": "https://bla2" } ], "failed_urls": ["https://gsl..."] }
Now let's replace all instances of "services-status" with "EXCELLENT":
updated_data = replace_key_value(original_data, "services-status", "EXCELLENT")
If you inspect updated_data, you'll see every services-status key now has the value "EXCELLENT", and the original original_data remains unchanged (thanks to the deep copy).
Optional: In-Place Modification
If you don't mind modifying the original data (and want to skip the deep copy for performance), you can simplify the function:
def replace_key_value_inplace(data, target_key, new_value): if isinstance(data, dict): for key, value in data.items(): if key == target_key: data[key] = new_value else: replace_key_value_inplace(value, target_key, new_value) elif isinstance(data, list): for item in data: replace_key_value_inplace(item, target_key, new_value) return data
Just note that this will alter your original dictionary directly.
内容的提问来源于stack exchange,提问作者Wilbur Dsouza

