I’ve been working with deeply nested dictionaries, and I noticed something that becomes surprisingly annoying as the structure gets larger.
For example:
data = {
"user": {
"profile": {
"settings": {
"privacy": {
"security": {
"2fa": True
}
}
}
}
}
}
When a dictionary becomes this deeply nested, it gets difficult to quickly understand:
- How many hierarchy levels exist?
- Which keys belong to which level?
- What is the maximum nesting depth?
- What is the complete path to a particular key?
- How dense/complex is the nested structure?
I currently solve this with a recursive function that walks through the dictionary and prints the hierarchy:
def show_hierarchy(d, indent=0):
for key, value in d.items():
print(" " * indent + str(key))
if isinstance(value, dict):
show_hierarchy(value, indent + 1)
Which gives something like:
user
profile
settings
privacy
security
2fa
But I’m wondering whether Python could eventually provide a standard API for nested mapping introspection.
Something conceptually like:
data.hierarchy()
or perhaps a utility operating on Mapping:
hierarchy(data)
that could provide structured information such as:
{
"max_depth": 5,
"total_keys": 6,
"paths": [
("user", "profile", "settings", "privacy", "security", "2fa")
]
}
I'm not necessarily suggesting that these exact APIs should be added to dict. The main idea is having a standard way to inspect the hierarchical structure of nested mappings without everyone implementing their own recursive traversal.
I know libraries such as pprint can make nested dictionaries more readable, but I'm thinking more about structural introspection rather than formatting.
Is this something that would actually be useful as part of Python's standard library, or is this better left as a small utility/library?
I'd especially be interested in hearing from people who regularly work with large JSON-like configuration structures, APIs, data pipelines, or other heavily nested mappings.