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

Question:

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.

Asked By: chrismint

||

Answers:

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.

Answered By: Barmar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.