Search code examples
pythonobjectnestedstructureprimitive

change variables in an unknown python structure


Lets say i have a list or dictionary, each one contains many dictionaries, lists, sets,string,floats, and so on. every time i need to handle different structure, but what i know is that all the strings (some of them in different level of nesting) have some extra spaces in them, so i need to trim them using :

if (type(variable)==str):
    variable=variable.strip()

How can i access all these variables given an unknown structure being = [' 1',2,3,{},[[],{}],9,9] or maybe {'1:2,2:[],9:[],10:[[[]]]} ? In case of dictionaries, the keys are ok (trimming won't change anything, so i don't mind doing it), just need to change the values Is there an elegant function for this?


Solution

  • Combination of recursion and checking for types will let you process a structure in a predetermined way without knowing its exact structure beforehand. You need to know how each specific container should be handled though.

    variable = {'1':2,2:[],9:[],10:[[[]]]}
    
    def custom_strip(variable):
        if isinstance(variable, dict):
            for k, v in variable.items():
                variable[k] = custom_strip(v)
            return variable
        if isinstance(variable, list):
            return [custom_strip(v) for v in variable]
        if isinstance(variable, set):
            return {custom_strip(v) for v in variable}
        if isinstance(variable, float) or isinstance(variable, int):
            return variable + 1
        if isinstance(variable, str):
            return variable.strip()
        raise TypeError("Unknown type")
    
    print(custom_strip(variable))