I'm using Python3 and I have some dict like the following one:
{
"test": "asdas",
"value": "REPLACE_ME",
"data": {
"data1": [
{
"key1": "REPLACE_ME"
},
{
"key2": "REPLACE_ME"
},
{
"key3": "asdasda"
}
],
"data2": "REPLACE_ME",
"data3": [
"REPLACE_ME",
"asdasdas",
"asdasda"
]
}
}
The structure is not consistent. This means that the structure could be different and REPLACE_ME can be in other places. I want to iterate over the data and replace REPLACE_ME with REPLACED in all places. If the structure was consistent, I would just iterate over the dict and check if the value is REPLACE_ME and replace it. But I don't know where the structure get nested. Given a dict (you don't know which, it could have lists in it, nested dicts or just basic fields), how would you replace REPLACE_ME with REPLACED in all places?
Replacing deep in a nested data structure is a naturally recursive problem, so it's natural to solve it with a recursive function:
def replace_deep(data, a, b):
if isinstance(data, str):
return data.replace(a, b)
elif isinstance(data, dict):
return {k: replace_deep(v, a, b) for k, v in data.items()}
elif isinstance(data, list):
return [replace_deep(v, a, b) for v in data]
else:
# nothing to do?
return data
I'm assuming here that you have something like JSON data so you want to recurse on nested dictionaries and lists, and there won't be tuples, sets or other containers. If there are, you can add extra cases to the function to fit your own needs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With