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
🌐
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.
🌐
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.
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 - 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 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. More on stackoverflow.com
🌐 stackoverflow.com
🌐
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.

🌐
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.
🌐
W3Schools
w3schools.com β€Ί python β€Ί python_dictionaries_nested.asp
Python - Nested Dictionaries
To access items from a nested dictionary, you use the name of the dictionaries, starting with the outer dictionary: ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com Β· If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com Β· HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
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
🌐
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

🌐
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 - For any nested dictionary, it finds it will flatten it in a way that the key renames to the full path. The flatten_dict() function has to be applied on each record in a list of dictionaries, meaning you can use either a Python loop or a list ...
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)
🌐
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 ...
🌐
GoLinuxCloud
golinuxcloud.com β€Ί home β€Ί python β€Ί nested dictionary in python [practical examples]
Nested dictionary in Python [Practical Examples] | GoLinuxCloud
December 31, 2023 - Notice that we have used nested for loop to iterate through the given dictionary because it was also nested. A nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary. In this tutorial, we learned about Python nested dictionaries.
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί python-how-to-iterate-over-nested-dictionary
Python – How to Iterate over nested dictionary ? | GeeksforGeeks
February 28, 2023 - Like List Comprehension, Python allows dictionary comprehensions. We can create dictionaries using simple expressions. A dictionary comprehension takes the form {key: value for (key, value) in iterable}Python Dictionary Comprehension ExampleHere we have two lists named keys and value and we are iter
🌐
Tutorialspoint
tutorialspoint.com β€Ί python β€Ί python_nested_dictionaries.htm
Python - Nested Dictionaries
We can iterate through a nested dictionary by using nested loops. The outer loop iterates over the keys and values of the main dictionary, while the inner loop iterates over the keys and values of the nested dictionaries.
🌐
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
🌐
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...
🌐
Learn By Example
learnbyexample.org β€Ί python-nested-dictionary
Python Nested Dictionary - Learn By Example
June 20, 2024 - In this example, the outer loop iterates over each item in the main dictionary D, while the inner loop iterates over each key-value pair within the nested dictionary info. To verify if a specific key exists within a nested dictionary, you can utilize the in operator. This operator allows you to check for the presence of a key at any level of the nested structure.