Skip to content
Advertisement

Python DFS nested dictionary

I’ve written a function which should be able to search a nested dictionary, using DFS, to find a specific value. The recursive element seems to be working fine, however, when the base case should return True, it simply doesn’t.

JavaScript

And the results. As you can see, the standard output “i==i” shows that this element was evaluated correctly but the return True statement isn’t functioning as intended. I’ve verified that if I call obj_dfs(obj, 'j'), that experiences the same error.

JavaScript

Why is this? And how can I fix this?

Advertisement

Answer

As the comments point out, you need to return the results of the recursive calls. Since you are just looking for a True/False match, you can pass the recursive calls into any() which will exit early with True if there is a match. The base case can simple be whether obj == target.

JavaScript

This allows for a three simple blocks. Notice we are checking for a tuple as well as a list in the last isinstance. This allows you to simply pass in the dict item()s rather than looping over keys and values independently.

Adding a print(obj) as the first line of the function will show the order in which you are traversing the data. For example obj_dfs(obj, 'j') will print:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement