Last active
September 1, 2023 15:01
-
-
Save samukasmk/b57122cc9db4724d4305b43d8d68484f to your computer and use it in GitHub Desktop.
[Recursion Algorithm In Practice] This script look for str objects in all sub childrens of a dict to replace values, using a recursion function.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def replace_dynamic_variable(element): | |
# If the element is a string, replace "{variable_dynamic}" with "hacked" | |
if isinstance(element, str): | |
element = element.replace("{variable_dynamic}", "hacked") | |
# If the element is a dictionary, iterate through each key-value pair | |
elif isinstance(element, dict): | |
for key, value in element.items(): | |
element[key] = replace_dynamic_variable(value) | |
# If the element is a list, iterate through each item | |
elif isinstance(element, list): | |
for i, value in enumerate(element): | |
element[i] = replace_dynamic_variable(value) | |
# If the element is a tuple, create a new tuple with replaced values | |
elif isinstance(element, tuple): | |
element = tuple(replace_dynamic_variable(list(element))) | |
# If the element is a set, create a new set with replaced values | |
elif isinstance(element, set): | |
element = {replace_dynamic_variable(value) for value in element} | |
# Return the element with possibly replaced values | |
return element | |
def replace_in_config(config): | |
return replace_dynamic_variable(config) | |
# Example usage: | |
original_config = { | |
'host': 'localhost', | |
'port': '{variable_dynamic}', | |
'credentials': { | |
'username': 'admin', | |
'password': '{variable_dynamic}', | |
'categories': [ | |
{'tag': '{variable_dynamic}'} | |
] | |
}, | |
'features': ['feature1', '{variable_dynamic}'], | |
'tuple_data': ('data1', '{variable_dynamic}'), | |
'set_data': {'data1', '{variable_dynamic}'} | |
} | |
modified_config = replace_in_config(original_config) | |
print(modified_config) | |
# {'host': 'localhost', | |
# 'port': 'hacked', | |
# 'credentials': { | |
# 'username': 'admin', | |
# 'password': 'hacked'}, | |
# 'categories': [{'tag': 'hacked'}]} | |
# 'features': ['feature1', 'hacked'], | |
# 'tuple_data': ('data1', 'hacked'), | |
# 'set_data': {'data1', 'hacked'}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment