Iterate over nested lists and dictionaries

前端 未结 1 834
隐瞒了意图╮
隐瞒了意图╮ 2021-01-13 16:22

I need to iterate over nested lists and dictionaries and replace every integer trough an hex string. Such an element could for example look like this:

eleme         


        
相关标签:
1条回答
  • 2021-01-13 16:23

    The function doesn't just return tuple elements; it returns the path to any item in the nested structure, plus it's value. You can use that path to get at the value and change it:

    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)
    

    So, for every value that is an integer, use the path to find the parent of that value, then replace the current value with it's hex equivalent.

    The output you get from the above method:

    >>> element
    {'Params': ['Typetext', ['0x10', '0x2'], '0x2'], 'Request': ['0x10', '0x2'], 'Responses': [{'State': 'Positive', 'PDU': ['0x50', '0x2', '0x0']}, {}], 'Service': 'Servicetext'}
    
    0 讨论(0)
提交回复
热议问题