Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to recursively iterate a nested Python dictionary?
A Dictionary in Python is a mutable, unordered collection of data in a key-value format. A dictionary can also contain another dictionary as a value and this is known as a Nested Dictionary or a dictionary within a dictionary. When working with this type of data structure, it's often important to go through each key-value pair at every level.
In this article, we will explore how to recursively iterate through a nested Python dictionary using a function-based approach.
Syntax to iterate through a Dictionary recursively
Following is a sample syntax for recursively iterating through a nested dictionary -
def recursive_iter(d):
for key, value in d.items():
if isinstance(value, dict):
recursive_iter(value)
else:print(key, ":", value)
Example to iterate through a Dictionary recursively
In this example, we define a nested dictionary with multiple dictionaries. The recursive function will print all keys and values from every level.
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)
Following is the output of the above program -
Entering nested dictionary at key: person name: John age: 30 Entering nested dictionary at key: address city: New York zip: 10001 Entering nested dictionary at key: job title: Developer department: Engineering
Advertisements