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) Answer from -aRTy- on reddit.com
🌐
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 - Creating a nested dictionary using a for loop might sound like a new concept but it is an easier and much more systematic approach to create a nested dictionary using a for loop which can then be used to loop through the nested data structure.
🌐
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.

Discussions

python - How to iterate through a nested dict? - Stack Overflow
I have a nested python dictionary data structure. I want to read its keys and values without using collection module. The data structure is like bellow. d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2... More on stackoverflow.com
🌐 stackoverflow.com
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. More on stackoverflow.com
🌐 stackoverflow.com
python - Creating a nested dictionaries via for-loop - Stack Overflow
I'm having trouble creating a dictionary with multiple keys and values inside an other dictionary by using a for-loop. I have a program that reads another text file, and then inputs it's informatio... More on stackoverflow.com
🌐 stackoverflow.com
How to iterate over nested dictionaries in a LIST, using for loop
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… More on community.dataquest.io
🌐 community.dataquest.io
5
0
January 7, 2021
🌐
GeeksforGeeks
geeksforgeeks.org › python › loop-through-a-nested-dictionary-in-python
Loop Through a Nested Dictionary in Python - GeeksforGeeks
July 23, 2025 - In this example, below Python code defines a recursive function, `iterate_nested_dict`, to iterate through a nested dictionary, printing each key-value pair. It handles nested structures by recursively calling itself when encountering inner dictionaries, providing a clear and flexible approach for nested dictionary traversal.
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)
🌐
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 - Sometimes we may need to go through all the values in a dictionary even if they are nested. Here we are going to see some methods to do it and we are going to show it by printing each key-value pair. As an example, let’s use a simple data structure that simulates the data of a programming course for children as shown in the figure.
Find elsewhere
🌐
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.
🌐
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. ... Inside the function, we iterated over all the key-value pairs of a given dictionary object and for each value object in the pair it checks if the value is of dict type or not.
🌐
YouTube
youtube.com › watch
How to Loop Through a Nested Dictionary with Python? - YouTube
Full Tutorial: https://blog.finxter.com/how-to-loop-through-a-nested-dictionary-with-python/Email Academy: https://blog.finxter.com/email-academy/►► Do you w...
Published   February 22, 2022
🌐
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'...
🌐
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 - 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. Then, we print Ice Cream: followed by the key associated with a particular ice cream. Next, we use another for loop to loop through every item in each value in our 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

🌐
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.
🌐
YouTube
youtube.com › watch
PYTHON TUTORIAL: NESTED DICTIONARY IN PYTHON||HOW TO LOOP THROUGH NESTED DICTIONARIES IN PYTHON - YouTube
Chapters:What is a nested dictionary: 0:44How to loop through nested dictionary: 12:12How to delete a specific element of dictionary: 20:30My Other Channel: ...
Published   August 27, 2022
Views   1K
🌐
Data Science Dojo
discuss.datasciencedojo.com › python
How to loop through all nested dictionary values in Python? - Python - Data Science Dojo Discussions
May 10, 2023 - I have a nested dictionary in Python, and I want to loop through all the values in it, including the values in the nested dictionaries. How can I do this? I have tried using nested loops, but they only iterate through the first level of values. Here is the sample code that I tried: This code ...
🌐
Squash
squash.io › iterating-and-looping-through-python-dictionaries
How to Iterate and Loop Through Python Dictionaries
Iterating over a nested dictionary requires nested loops. You can use a combination of for loops and dictionary methods to loop through the keys and values at each level.