Click here to Skip to main content
15,745,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How would I recursively check a dictionary which contains nested dictionaries.

So the dictionary would go like this:
dict = {"1": {"1.1": {"x", "x", "x"},
              "1.2": {"y", "y", "y"}},
        "2": {"2.1": {"z", "z", "z"}},
        "3": {"3.1": {"a"}}}

How would I loop through the entire dict?
I am searching the dict by keys so if I put in like 1.2, it would write out everything until it finds that key.

1, 1.1, 1.2

What I have tried:

Ok so to go throught the first layer I do the normal for loop:

def recursion(item):
    for i in stiki:

What would be the correct way to recursivly call a dictionary like that?
Updated 1-Jan-21 9:40am
Richard MacCutchan 16-Dec-20 12:53pm    
The key is to know when your dictionary contains normal entries, and when it contains further dictionaries.

You need to study the technique.
Just like with any recursive algorithm, at any point, you need to know if there is matter to recursion, in your case, is there a sub-directory.
def recursion(item):
    for i in stiki: # what is stiki here ? I would have expected item instead.

Recursion (computer science) - Wikipedia[^]
Share this answer
def recursion(my_dict):
	for x, y in my_dict.items():
		if isinstance(y, dict):

isinstance() checks if first argument is of type specified in the second argument, in this case it checks if y is of type 'dict', if it is then continue with the recursion, or else print it.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900