Better patter for nested for loops -- recusion

27 Views Asked by At

I have a dictionary that is made up of nested dictionaries and lists. I need to search it and pull out selected sub elements. Everything is working fine but I feel like there a better way to drive it. Right now I have a number of nested for loops.

import xmltodict
import helper
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

with open('fav_all.xml') as in_xml:
    d = xmltodict.parse(in_xml)
    for k0, v0 in d.items():
        for l1 in helper.type_checker(v0):
            for l2 in helper.type_checker(l1):
                for l3 in helper.type_checker(l2):
                    for l4 in helper.type_checker(l3):
                        for l5 in helper.type_checker(l4):
                            for l6 in helper.type_checker(l5):
                                for l7 in helper.type_checker(l6):
                                    for l8 in helper.type_checker(l7):
                                        for l9 in helper.type_checker(l8):
                                            print 'yield'

The helper type checker yields the next part of the nested structure or if it finds the right sub part it process it for output.

def type_checker(x):
    if isinstance(x, list):
        for i in x:
            if isinstance(i, OrderedDict):
                yield i
    elif isinstance(x, OrderedDict):
        for k, v in x.items():
            if k in tag_list:
                if k == 'DESCRIPTION':
                    print '{k}: {v}'.format(k=k, v=v)
                elif k == 'GISUNIT':
                    process_unit(v)
                    yield 'end'
                else:
                    yield v

1

There are 1 best solutions below

0
fallingdog On

I changed the for loop into the below structure and it worked.

def looper(x):
    for y in helper.type_checker(x):
        looper(y)


with open('fav_all.xml') as in_xml:
    d = xmltodict.parse(in_xml)
    for k0, v0 in d.items():
        looper(v0)