Nice to see xterm switch from Java :P (I've been away a while)
Python solution, doesn't use stacks(just a simple queue) and does the replacing inline(doable not in-line but would unnecessarily complicate the code for now):
def inplace_iterative_action(data, action):
result = {}
queue = [data]
while queue:
node = queue.pop(0)
for key,value in node.items():
if type(value) == str:
node[key] = action(value)
else:
queue.append(value)
return data
Full example to see it in action:
import pprint
data = {
'a': '1',
'b': '2',
'c': {
'd': '3',
'e': { 'f': '4' },
'g': { 'h': '5' },
'i': '6'
},
'j': '7'
}
def inplace_iterative_action(data, action):
result = {}
queue = [data]
while queue:
node = queue.pop(0)
for key,value in node.items():
if type(value) == str:
node[key] = action(value)
else:
queue.append(value)
return data
pprint.pprint(data)
print
inplace_iterative_action(data, lambda a:"replaced")
pprint.pprint(data)
Result:
{'a': '1',
'b': '2',
'c': {'d': '3', 'e': {'f': '4'}, 'g': {'h': '5'}, 'i': '6'},
'j': '7'}
{'a': 'replaced',
'b': 'replaced',
'c': {'d': 'replaced',
'e': {'f': 'replaced'},
'g': {'h': 'replaced'},
'i': 'replaced'},
'j': 'replaced'}