简体   繁体   中英

Python recursion with yield and return in nested dictionary

I'm trying to learn the use of yield and return in recursive function. I've a nested dictionary where I'm searching for a particular value.

When using "yield", the following function runs fine and returns the found value successfully:

def findvalue (value, document):
    if isinstance (document, list):
        for d in document:
            for result in findvalue(value, d):
                yield result
    if isinstance (document, dict):
        for k,v in document.items():
            if v == value:
                yield v
            elif isinstance (v, dict):
                for result in findvalue(value, v):
                    yield result
            elif isinstance (v, list):
                for d in v:
                    for result in findvalue(value, d):
                        yield result

I understand how generator works and why yield does what it does in above code. Now if I use the same code, but with return and put a check in there to check for empty return, I still end up with "NoneType" iteration issue because somewhere an empty result is being returned in this code:

def valuefind (value, document):
    if isinstance (document, list):
        for d in document:
            for result in valuefind(value, d):
                if result is not None:
                    return result          
    if isinstance (document, dict):
        for k, v in document.items():
            if v == value:
                return v
            elif isinstance (v, dict):
                for result in valuefind(value, v):
                    if result is not None:
                        return result
            elif isinstance (v, list):
                for d in value:
                    for result in valuefind(value, d):
                        if result is not None:
                            return result

What am I missing here?

I believe you can change this:

for result in valuefind(value, v):
                    if result is not None:
                        return result

To this:

return valuefind(value, v)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM