Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

See if value exists in Python nested dict which contains dicts, lists, and strings

I’m not sure if there is some library that handles this, or if recursion is the way to go. I am trying to write a recursion function, when I call it it always ends up returning False. Any help appreciated.

item starts out as a dict.
text is a string to match.

def match(item, text):
    if item == text:
        return True
    if type(item) == list:
        for i in item:
            match(i, text)
    if type(item) == dict:
        for i in item.values():
             match(i text)
    return False

I’m not quite grasping how to have it keep going when say the first item of a list is not a match.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re not returning True when the recursive call finds a match.

def match(item, text):
    if item == text:
        return True
    if isinstance(item, (list, tuple)):
        return any(match(i, text) for i in item)
    if isinstance(item, dict):
        return any(match(i, text) for i in item.values())
    return False

You should also use isinstance() for type checks, to allow for subclasses.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading