
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to recursively iterate a nested Python dictionary?
Given below is a nested directory object
D1={1: {2: {3: 4, 5: 6}, 3: {4: 5, 6: 7}}, 2: {3: {4: 5}, 4: {6: 7}}}
Example
Following recursive function is called repetitively if the value component of each item in directory is a directory itself.
def iterdict(d): for k,v in d.items(): if isinstance(v, dict): iterdict(v) else: print (k,":",v) iterdict(D1)
Output
When the initial dictionary object is passed to this function, all the key-value pairs are traversed. The output is:
3 4 5 6 4 5 6 7 4 5 6 7
- Related Articles
- How to sort a nested Python dictionary?
- How to iterate through a dictionary in Python?
- How to create nested Python dictionary?
- How to count elements in a nested Python dictionary?
- Iterate over a dictionary in Python
- How to Iterate over Tuples in Dictionary using Python
- How to iterate over a C# dictionary?
- Python Convert nested dictionary into flattened dictionary?
- Python - Convert flattened dictionary into nested dictionary
- How to access nested Python dictionary items via a list of keys?
- Python Pandas - Convert Nested Dictionary to Multiindex Dataframe
- C++ Program to Iterate Over a Dictionary
- Recursively list nested object keys JavaScript
- Convert Nested Tuple to Custom Key Dictionary in Python
- How to create a directory recursively using Python?

Advertisements