Iterate over nested lists, tuples, and dictionaries

I have one more question about Iteration on nested lists and dictionaries .

I need advanced functionality for the topic above. The iterable element now also contains tuples . Also, integers in tuples must be converted to a hexadecimal string. So I tried with the following code to convert tuples to lists.

for path, value in objwalk(element): if isinstance(value, tuple): parent = element for step in path[:-1]: parent = parent[step] parent[path[-1]] = list(value) 

But my problem is that tuples in tuples are not converted. How can I convert "substrings" to lists in an elegant way?

Regards Wewa

PS: I created a new theme because something else was fixed for me.

+3
source share
2 answers

In this case, it would be easier to process the tuples directly in the objwalk structure objwalk . Here is a modified version that converts tuples to lists before moving through them to find nested elements:

 def objwalk(obj, path=(), memo=None): if memo is None: memo = set() iterator = None if isinstance(obj, dict): iterator = iteritems elif isinstance(obj, (list, set)) and not isinstance(obj, string_types): iterator = enumerate if iterator: if id(obj) not in memo: memo.add(id(obj)) for path_component, value in iterator(obj): if isinstance(value, tuple): obj[path_component] = value = list(value) for result in objwalk(value, path + (path_component,), memo): yield result memo.remove(id(obj)) else: yield path, obj 

Using a slightly modified example from your previous question and the same hex solution I gave you in this question:

 >>> element = {'Request': (16, 2), 'Params': ('Typetext', [16, 2], 2), 'Service': 'Servicetext', 'Responses': ({'State': 'Positive', 'PDU': [80, 2, 0]}, {})} >>> for path, value in objwalk(element): ... if isinstance(value, int): ... parent = element ... for step in path[:-1]: ... parent = parent[step] ... parent[path[-1]] = hex(value) ... >>> element {'Params': ['Typetext', ['0x10', '0x2'], '0x2'], 'Request': ['0x10', '0x2'], 'Responses': [{'State': 'Positive', 'PDU': ['0x50', '0x2', '0x0']}, {}], 'Service': 'Servicetext'} 
+1
source

If the overhead of creating new objects is not a problem, I think this is pretty clear:

 def transform(obj): _type = type(obj) if _type == tuple: _type = list rslt = _type() if isinstance(obj, dict): for k, v in obj.iteritems(): rslt[k] = transform(v) elif isinstance(obj, (list, tuple)): for x in obj: rslt.append(transform(x)) elif isinstance(obj, set): for x in obj: rslt.add(transform(x)) elif isinstance(obj, (int, long)): rslt = hex(obj) else: rslt = obj return rslt element = transform(element) 
+1
source

All Articles