Is there a general way to traverse and replace the items in a nested sequence of arbitrary depth? Say, for instance, that I want to eliminate all the commas in any strings in some absurd nested sequence object, maybe one of which looks something like this:
I can do something like this:
But that only works for the types I've explicitly checked for, and we're always told we're doing something wrong if we're type-checking in Python anyway. I tried coming up with something using __iter__(), but I ran into problems needing to recreate the nested objects, since some sequences are immutable, and there are multiple ways of doing indexing (e.g., dictionaries must be reference by key). There is also more than one iteration protocol in Python—for instance, strings don't use __iter__() at all.
What's the Pythonic way to do this?
Code:
{'key1': ['string with, a comma', ['another string with, a comma']], 'key2': ('this one, is in a tuple', \
{'key3': ['that also, has a dictionary in it]}, 'you get, the point'), 'key4': 'I, hope'}
I can do something like this:
Code:
from copy import deepcopy
def kill_commas(container):
"""finds any COMMA lurking in any string anywhere in a standard sequence object,
including in a nested sequence of sequences of arbitrary depth, and DESTROYS it"""
copy = deepcopy(container)
if isinstance(copy, str):
return copy.replace(',', '')
else:
if isinstance(copy, list):
for i, v in enumerate(copy):
copy[i] = kill_commas(v)
elif isinstance(copy, tuple):
copy = list(copy)
for i, v in enumerate(copy):
copy[i] = kill_commas(v)
copy = tuple(copy)
elif isinstance(copy, dict):
for k in copy.keys():
copy[k] = kill_commas(copy[k])
return copy
What's the Pythonic way to do this?