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
๐ŸŒ
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
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 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
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
Ways to improve efficiency in looping through a nested dictionary
Not really, there's 3 different levels and you can't avoid it without iterating at each level. You could make it look a little "nicer", potentially, but using a recursive function that iterates only the current level and calls itself for each nested level, but then you have to check if you're at the "leaf" level to know whether you need to print or not. More on reddit.com
๐ŸŒ r/learnprogramming
3
1
October 5, 2022
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
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'...
Find elsewhere
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
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())
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ datastructures.html
5. Data Structures โ€” Python 3.14.6 documentation
Note: to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section. Because sets are unordered, iterating over them or printing them can produce the elements in a different order than you expect.
Top answer
1 of 2
4

Well I can suggest a semi-hacky solution where you use set_fact a couple times to construct a list of dicts that you can probably use?

- hosts: localhost
  vars:
    nova_flavors:
    - disk: 10
      name: m1.tiny
      properties:
        disk_read_bytes_sec: 12500000
        disk_read_iops_sec: 1000
        disk_write_bytes_sec: 3125000
      ram: 1
    - disk: 10
      name: m1.small
      properties:
        vif_outbound_burst: 7500000
        vif_outbound_peak: 25000
      ram: 2
  tasks:
  - set_fact:
      aslist: |
        [
        {% for item in nova_flavors %}
        {% for prop in item.properties.keys() %}
        {{ '{' }} 'name':'{{ item.name }}','propname':'{{ prop }}','propvalue':{{item.properties[prop]}} {{ '}' }},
        {% endfor %}
        {% endfor %}
        ]

  - debug:
      var: aslist

Results.

TASK [debug] *******************************************************************
ok: [localhost] => {
    "aslist": [
        {
            "name": "m1.tiny", 
            "propname": "disk_write_bytes_sec", 
            "propvalue": 3125000
        }, 
        {
            "name": "m1.tiny", 
            "propname": "disk_read_iops_sec", 
            "propvalue": 1000
        }, 
        {
            "name": "m1.tiny", 
            "propname": "disk_read_bytes_sec", 
            "propvalue": 12500000
        }, 
        {
            "name": "m1.small", 
            "propname": "vif_outbound_peak", 
            "propvalue": 25000
        }, 
        {
            "name": "m1.small", 
            "propname": "vif_outbound_burst", 
            "propvalue": 7500000
        }
    ]
}

PLAY RECAP *********************************************************************
localhost                  : ok=4    changed=0    unreachable=0    failed=0   

I believe this would easily allow you to loop over the constructed lists setting the each property.

2 of 2
1

If I ignore the "I want to check the value first" part, I could solve this through templating instead, like this:

- name: set flavor properties:
  command: >-
    openstack flavor set
    {%for prop in item.properties.items()%}--property
    {{prop.0}}={{prop.1}} {%endfor %} {{ item.name }}
  loop: "{{ nova_flavors }}"

That works, but it's ugly, and will result in everything being changed every playbook run. I could munge the data before passing it to ansible so that the properties keys is a list of lists instead of a list of dicts, as in:

- disk: 10
  name: m1.tiny
  properties:
    - [disk_read_bytes_sec,  12500000]
    - [disk_read_iops_sec,  1000]
    - [disk_write_bytes_sec,  3125000]
    - [disk_write_iops_sec,  250]
    - [vif_inbound_average,  2500]
    - [vif_inbound_burst,  3750000]
    - [vif_inbound_peak,  12500]
    - [vif_outbound_average,  2500]
    - [vif_outbound_burst,  3750000]
    - [vif_outbound_peak,  12500]
  ram: 1
  vcpus: 1
- disk: 10
  name: m1.small
  properties:
    - [disk_read_bytes_sec: 25000000]
    - [disk_read_iops_sec: 2000]
    - [disk_write_bytes_sec: 6250000]
    - [disk_write_iops_sec: 500]
    - [vif_inbound_average: 5000]
    - [vif_inbound_burst: 7500000]
    - [vif_inbound_peak: 25000]
    - [vif_outbound_average: 5000]
    - [vif_outbound_burst: 7500000]
    - [vif_outbound_peak: 25000]
  ram: 2
  vcpus: 1

But that's somewhat less intuitive to read and write...and it's effectively re-implementing the .items() method by hand.

๐ŸŒ
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.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-iterate-over-a-dictionary-in-python
How to iterate over a dictionary in Python
The fastest way to iterate over a dictionary in Python is using the items() method, which returns both keys and values in each iteration, avoiding extra lookups.
๐ŸŒ
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 ...
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_dictionaries_loop.asp
Python - Loop Dictionaries
Python Examples Python Compiler ... Q&A Python Bootcamp Python Training ... You can loop through a dictionary by using a for loop....
๐ŸŒ
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)