The following will work with multiple levels of nested-dictionary:

def get_all_keys(d):
    for key, value in d.items():
        yield key
        if isinstance(value, dict):
            yield from get_all_keys(value)


d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'dict3': {'baz': 3, 'quux': 4}}}
for x in get_all_keys(d):
    print(x)

This will give you:

dict1
foo
bar
dict2
dict3
baz
quux
Answer from 0x0 on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › loop-through-a-nested-dictionary-in-python
Loop Through a Nested Dictionary in Python - GeeksforGeeks
July 23, 2025 - It provides a clear representation of the hierarchical structure of the nested dictionary. ... nested_dict = {'outer_key': {'inner_key1': 'value1', 'inner_key2': 'value2'}} for outer_key, inner_dict in nested_dict.items(): print(f"Outer Key: {outer_key}") for inner_key, value in inner_dict.items(): print(f"Inner Key: {inner_key}, Value: {value}") ... In this example, below Python code defines a recursive function, `iterate_nested_dict`, to iterate through a nested dictionary, printing each key-value pair.
Discussions

How to loop through a nested dictionary
You don't need to loop through keys to find the key, you can just access a value via the key. That's the whole point of a dictionary. Have a look at the two following examples outer_dict = {"outer_key": {"inner_key": "value_string"}} # getting things step by step inner_dict = outer_dict["outer_key"] value = inner_dict["inner_key"] print(value) # jumping right to the value value = outer_dict["outer_key"]["inner_key"] print(value) More on reddit.com
🌐 r/learnpython
5
2
May 6, 2024
How to loop over nested dictionaries of n length?
Yes recursion. Base case is if empty dictionary or None, return. Otherwise do the work on the dictionary you want More on reddit.com
🌐 r/learnpython
11
2
March 17, 2021
python - Loop through all nested dictionary values? - Stack Overflow
I'm trying to loop through a dictionary and print out all key value pairs where the value is not a nested dictionary. If the value is a dictionary I want to go into it and print out its key value pairs, etc. I tried this. But it only works for the first two levels. I need it to work for any number of levels. Copyfor k, v in d.iteritems... More on stackoverflow.com
🌐 stackoverflow.com
python - Iterate through nested dictionary - Stack Overflow
Im trying to create a function increase_by_one which takes in a dictionary and modifies the dictionary by increasing all values in it by 1. The function should remain all keys unchanged and finally More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-how-to-iterate-over-nested-dictionary
Python - How to Iterate over nested dictionary ? - GeeksforGeeks
February 28, 2023 - Similarly to get values, after each iteration values() function is used to get the job done. ... # create a nested dictionary with 3 fields of 3 students data = { 'Student 1': {'Name': 'Bobby', 'Id': 1, "Age": 20}, 'Student 2': {'Name': 'ojaswi', 'Id': 2, "Age": 22}, 'Student 3': {'Name': 'rohith', 'Id': 3, "Age": 20}, } # iterate all the nested dictionaries with values for i in data: # display print(data[i].values())
🌐
Reddit
reddit.com › r/learnpython › how to loop through a nested dictionary
r/learnpython on Reddit: How to loop through a nested dictionary
May 6, 2024 -

Hiya, I'm developing a game as a hobby, and I am currently coding in a clothing shop. Every piece of clothing has a description, cost, and stat requirements. To organise this data, I've used nested dictionaries within a few class attributes.

Now I want the shopkeeper to have specific comment for some clothing brought, so I'd want to return/print the description every time a player buys a piece of clothing? How would I do that exactly?

My pseudo code/problem strategy has been to write a function, initiate a loop over the keys of the outer dictionary, then using a conditional to find the piece of clothing just brought, and looping through it's inner dictionary to find it's dictionary key, and printing out it's value, which is a string. Hope that helps you understand my thinking.

🌐
Towards Data Science
towardsdatascience.com › home › latest › nested dictionary python - a complete guide to python nested dictionaries
Nested Dictionary Python - A Complete Guide to Python Nested Dictionaries | Towards Data Science
January 22, 2025 - An alternative way to create a nested dictionary in Python is by using the zip() function. It's used to iterate over two or more iterators at the same time.
🌐
Career Karma
careerkarma.com › blog › python › python nested dictionary: a how-to guide
Python Nested Dictionary: A How-To Guide | Career Karma
December 1, 2023 - First, we have defined our nested dictionary of ice cream flavors. Then, we have defined a for loop that goes through each key and value in the ice_cream_flavors dictionary. This loop uses .items() to generate a list of all the keys and values in our ice_cream_flavors dictionary, over which the loop can iterate.
🌐
thisPointer
thispointer.com › home › dictionary › python: how to iterate over nested dictionary -dict of dicts
Python: How to Iterate over nested dictionary -dict of dicts - thisPointer
April 13, 2021 - Using the function nested_dict_pair_iterator() we iterated over all the values of a dictionary of dictionaries and printed each pair including the parent keys.
Find elsewhere
🌐
Learn By Example
learnbyexample.org › python-nested-dictionary
Python Nested Dictionary - Learn By Example
June 20, 2024 - In this example, the deep_update function iterates through the keys and values of the second dictionary. If a value is itself a dictionary (a collections.abc.Mapping), the function recursively calls itself to merge the nested dictionaries. Otherwise, it simply updates the value in the source dictionary.
🌐
Reddit
reddit.com › r/learnpython › how to loop over nested dictionaries of n length?
r/learnpython on Reddit: How to loop over nested dictionaries of n length?
March 17, 2021 -

Hey there,

I have an dictionary (essentially json) and I'm trying to iterate over it. I cant share the dictionary but essentially i dont know how many times it will be nested. If it isn't nested there is data i need to return. Issue is depending on one of the values, it might have another dictionary i need to loop over. I'm having trouble conceptualizing how to even write this.

The stupid in me pictures it as a for loop for each nest (just assume ill never see a nesting of more than 10) and write the outputs i need to another list. I think the better way to handle this is recursion but I'm not super confident with it.

Is there any other way i can access all items of each nest without knowing how many nests?

Sorry if this is very arbitrary. I'm having difficulty myself even trying to explain it.

Cheers

Top answer
1 of 16
222

As said by Niklas, you need recursion, i.e. you want to define a function to print your dict, and if the value is a dict, you want to call your print function using this new dict.

Something like :

def myprint(d):
    for k, v in d.items():
        if isinstance(v, dict):
            myprint(v)
        else:
            print("{0} : {1}".format(k, v))
2 of 16
71

There are potential problems if you write your own recursive implementation or the iterative equivalent with stack. See this example:

dic = {}
dic["key1"] = {}
dic["key1"]["key1.1"] = "value1"
dic["key2"]  = {}
dic["key2"]["key2.1"] = "value2"
dic["key2"]["key2.2"] = dic["key1"]
dic["key2"]["key2.3"] = dic

In the normal sense, nested dictionary will be a n-nary tree like data structure. But the definition doesn't exclude the possibility of a cross edge or even a back edge (thus no longer a tree). For instance, here key2.2 holds to the dictionary from key1, key2.3 points to the entire dictionary(back edge/cycle). When there is a back edge(cycle), the stack/recursion will run infinitely.

            root<-------back edge
          /      \           |
       _key1   __key2__      |
      /       /   \    \     |
 |->key1.1 key2.1 key2.2 key2.3
 |   /       |      |
 | value1  value2   |
 |                  | 
cross edge----------|

If you print this dictionary with this implementation from Scharron

def myprint(d):
    for k, v in d.items():
        if isinstance(v, dict):
            myprint(v)
        else:
            print "{0} : {1}".format(k, v)
            

You would see this error:

> RuntimeError: maximum recursion depth exceeded while calling a Python object

The same goes with the implementation from senderle.

Similarly, you get an infinite loop with this implementation from Fred Foo:

def myprint(d):
    stack = list(d.items())
    while stack:
        k, v = stack.pop()
        if isinstance(v, dict):
            stack.extend(v.items())
        else:
            print("%s: %s" % (k, v))

However, Python actually detects cycles in nested dictionary:

print dic
{'key2': {'key2.1': 'value2', 'key2.3': {...}, 
       'key2.2': {'key1.1': 'value1'}}, 'key1': {'key1.1': 'value1'}}

"{...}" is where a cycle is detected.

As requested by Moondra this is a way to avoid cycles (DFS):

def myprint(d): 
    stack = list(d.items()) 
    visited = set() 
    while stack: 
        k, v = stack.pop() 
        if isinstance(v, dict): 
            if k not in visited: 
                stack.extend(v.items()) 
        else: 
            print("%s: %s" % (k, v)) 
        visited.add(k)
🌐
Python Central
pythoncentral.io › how-to-iterate-through-a-dictionary-in-python
How to Iterate Through a Dictionary in Python | Python Central
November 19, 2024 - Handle nested dictionaries: Be aware of nested dictionaries and use the appropriate techniques to traverse them. Consider using OrderedDict: Use OrderedDict if you need to preserve the insertion order of the dictionary. Avoid modifying the dictionary during iteration: Modifying the dictionary while iterating through it can lead to unexpected behavior. If you need to modify the dictionary, consider creating a copy or using a separate loop. ... Python ...
🌐
Programiz
programiz.com › python-programming › nested-dictionary
Python Nested Dictionary (With Examples)
In the above program, we delete both the internal dictionary 3 and 4 using del from the nested dictionary people. Then, we print the nested dictionary people to confirm changes. Using the for loops, we can iterate through each elements in a nested dictionary.
🌐
Squash
squash.io › iterating-and-looping-through-python-dictionaries
How to Iterate and Loop Through Python Dictionaries
August 25, 2023 - In this example, we use the items() method to iterate over the key-value pairs in the person dictionary. If a value is itself a dictionary (checked using isinstance()), we iterate over its key-value pairs as well.
🌐
Finxter
blog.finxter.com › home › learn python blog › how to loop through a nested dictionary with python?
How to Loop Through a Nested Dictionary with Python? - Be on the Right Side of Change
May 21, 2022 - The first yield after the if is to be able to show the nested keys, as in the other methods, but it is not essential. Another possibility is using the ABC module. This provides some abstract base classes that, as said in the Python documentation, can be used to test whether a class or instance provides a particular interface, for example, if it is hashable or if it is a mapping. A dictionary corresponds to the ABC class called “Mutable.Mapping“, which in turn is a subclass of “Mapping“.
🌐
TutorialsPoint
tutorialspoint.com › how-to-recursively-iterate-a-nested-python-dictionary
How to recursively iterate a nested Python dictionary?
June 7, 2025 - def recursive_iter(d): for key, value in d.items(): if isinstance(value, dict): print(f"Entering nested dictionary at key: {key}") recursive_iter(value) else: print(f"{key}: {value}") # Nested Dictionary data = { 'person': { 'name': 'John', 'age': 30, 'address': { 'city': 'New York', 'zip': '10001' } }, 'job': { 'title': 'Developer', 'department': 'Engineering' } } # Call the function recursive_iter(data)
🌐
Reddit
reddit.com › r/learnpython › iterate through nested dictionary and grab like values.
r/learnpython on Reddit: Iterate through nested dictionary and grab like values.
March 25, 2017 -

I made a post yesterday regarding how to iterate through a nested dict and ended up finding the answer before someone replied but my confusion is going one step deeper. The code below is a simple nested dict:

stuff = {
    'thing1' : { 'num' : '1.1.1.1', 'name' : 'jeff'},
    'thing2' : { 'num' : '1.1.1.2', 'name' : 'jim'},
    'thing3' : { 'num' : '1.1.1.3', 'name' : 'jim'}
}

How can I iterate through this dictionary and create groups based on the name.

For example, the output should be:

jim = '1.1.1.2', '1.1.1.3'

jeff = '1.1.1.1'

Basically I'm trying to take the name and if the name is the same all the nums with the same name should be output together.