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

Copydef 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:

Copydict1
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 - In conclusion, looping through a nested dictionary in Python involves using techniques like nested loops, recursion, `itertools.chain`, `dict.items()` with recursion, or leveraging `json.dumps` and `json.loads`. The choice depends on factors such as the structure of the nested dictionary and specific task requirements.
Discussions

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 p... More on stackoverflow.com
๐ŸŒ stackoverflow.com
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 - How to iterate through this nested dictionary within a list using for loop - Stack Overflow
@Tserenjamts I don't think it's a duplicate since my problem is a nested dictionary within a list, and also because I need it to be in dictionary form since I would want to export it into a csv later. I would also want it to be iterated through the nested dicts using a for loop since there ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Dataquest Community
community.dataquest.io โ€บ q&a โ€บ non-dq courses
How to iterate over nested dictionaries in a LIST, using for loop - Non-DQ Courses - Dataquest Community
January 7, 2021 - Hi there, I would like to extract the second key of every dictionary using a for loop. However, the dictionaries are nested in a list (see below). Also, notice that the second key is not always the same (this is where I am struggling). video_Ids = [ {'kind': 'youtube#playlist', 'playlistId': 'PLt1O6njsCRR-D_1jUAhJrrDZyYL6OZSGa'}, {'kind': 'youtube#playlist', 'playlistId': 'PLt1O6njsCRR_8oi7E6qnPWGQbn8NoQ6sG'}, {'kind': 'youtube#channel', 'channelId': 'UC4i5R6-IW05iiU8Vu__vppA'}, {'kind'...
๐ŸŒ
AskPython
askpython.com โ€บ home โ€บ how to create a nested dictionary via for loop?
How to Create a Nested Dictionary via for Loop? - AskPython
March 25, 2023 - Next, an empty dictionary named data is created to contain the nested dictionary. In the third line, we ask the user to specify the number of people to include. This is the value stored in n. This input iterates through the for loop.
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)
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-how-to-iterate-over-nested-dictionary
Python - How to Iterate over nested dictionary ? - GeeksforGeeks
February 28, 2023 - # 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 # both keys and values for i in data: # display print(data[i]) ... {'Name': 'Bobby', 'Id': 1, 'Age': 20} {'Name': 'ojaswi', 'Id': 2, 'Age': 22} {'Name': 'rohith', 'Id': 3, 'Age': 20} ... It is also possible to get only either keys or values if the that is what the requirement asks for. Again for this for loop is employed with a little variation.
๐ŸŒ
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.

Find elsewhere
๐ŸŒ
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.
๐ŸŒ
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

๐ŸŒ
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 - In this example, we first check if the value is a dictionary. If so, we iterate through the nested dictionary and print the key-value pairs.
๐ŸŒ
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.
๐ŸŒ
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 - For all this, if I had to choose, I would start by trying method 1 with either of the two variants, using d.items() or iterating directly on the dictionary as indicated in the additional tip.
๐ŸŒ
Squash
squash.io โ€บ iterating-and-looping-through-python-dictionaries
How to Iterate and Loop Through Python Dictionaries
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. This allows us to print all the keys and values within the nested dictionary. Related Article: Converting cURL Commands to Python
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ how-to-loop-three-level-nested-python-dictionary
How to Loop Three Level Nested Python Dictionary - GeeksforGeeks
July 23, 2025 - The recursiveFn function iterates through the key-value pairs, printing the current key with appropriate indentation based on the level. If the value is a nested dictionary, the function is called recursively with an incremented level.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-iterate-over-a-dictionary-in-python
How to iterate over a dictionary in Python
When dealing with nested dictionaries, you can use nested loops to iterate through both outer and inner dictionaries. nested_dict = {'a': {'x': 1, 'y': 2}, 'b': {'x': 3, 'y': 4}} ... The map() function can be used to apply a function to each ...
๐ŸŒ
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.
๐ŸŒ
StrataScratch
stratascratch.com โ€บ blog โ€บ how-to-iterate-over-a-dictionary-in-python
How to Iterate Over a Dictionary in Python? - StrataScratch
December 11, 2025 - There are primarily two approaches to iterate over nested dictionaries, which include using nested for loops and recursive iteration, respectively.
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-6966.html
Looping to Create Nested Dictionary
Hello! My code is supposed to read lines from a file that contains several attributes: assignment number, assignment name, grade, total, and weight. Each line of the file has this format. My code reads the lines and turns it into a nested dictiona...