15,745,005 members
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:
print(recursion(i))```

What would be the correct way to recursivly call a dictionary like that?
Posted
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.

Solution 1

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.
Python
```def recursion(item):
for i in stiki: # what is stiki here ? I would have expected item instead.
print(recursion(i))```

Recursion (computer science) - Wikipedia[^]

Solution 2

```def recursion(my_dict):
for x, y in my_dict.items():
if isinstance(y, dict):
recursion(y)
else:
print(y)```

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.