Iterate Over Nested Lists, Tuples And Dictionaries
I've another question to the thematic of Iterate over nested lists and dictionaries. I need some extended functionality to the topic of the link above. The iterable element now als
Solution 1:
In this case, it would be easier to handle tuples directly in the objwalk
structure traverser. Here is a modified version that converts tuples to lists before traversing over them to find nested elements:
defobjwalk(obj, path=(), memo=None):
if memo isNone:
memo = set()
iterator = Noneifisinstance(obj, dict):
iterator = iteritems
elifisinstance(obj, (list, set)) andnotisinstance(obj, string_types):
iterator = enumerateif iterator:
ifid(obj) notin memo:
memo.add(id(obj))
for path_component, value in iterator(obj):
ifisinstance(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 that 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):
... ifisinstance(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'}
Solution 2:
If the overhead of creating new objects is not an issue, I think it's pretty clear to go with:
deftransform(obj):
_type = type(obj)
if _type == tuple: _type = list
rslt = _type()
ifisinstance(obj, dict):
for k, v in obj.iteritems():
rslt[k] = transform(v)
elifisinstance(obj, (list, tuple)):
for x in obj:
rslt.append(transform(x))
elifisinstance(obj, set):
for x in obj:
rslt.add(transform(x))
elifisinstance(obj, (int, long)):
rslt = hex(obj)
else:
rslt = obj
return rslt
element = transform(element)
Post a Comment for "Iterate Over Nested Lists, Tuples And Dictionaries"