Skip to content

Instantly share code, notes, and snippets.

@shivams
Last active December 17, 2023 00:35
Show Gist options
  • Save shivams/e968bcd75818aa024b4d038a8319cb52 to your computer and use it in GitHub Desktop.
Save shivams/e968bcd75818aa024b4d038a8319cb52 to your computer and use it in GitHub Desktop.
Summarize Nested Python Dict
def summarize_dict_structure_v3(d, indent=0):
"""Recursively prints the structure of a nested dictionary, including lists.
If a list has multiple elements, it iterates only over the first element.
IMP NOTE: It assumes that a nested list would have uniform elements of same type,
so it doesn't iterate over the whole list, rather looks at its first element.
"""
for key, value in d.items():
print(' ' * indent + str(key), end=': ')
if isinstance(value, dict):
print("{Dictionary}")
summarize_dict_structure_v3(value, indent + 1)
elif isinstance(value, list):
print("[List of {} elements]".format(len(value)))
if value: # Check if the list is not empty
print(' ' * (indent + 1) + "List elements type: ", end='')
# Check the type of the first element in the list
if isinstance(value[0], dict):
print("dict")
summarize_dict_structure_v3(value[0], indent + 2)
else:
print(type(value[0]).__name__)
else:
print(type(value).__name__)
# Example nested dictionary with list containing dictionaries
nested_dict_v3 = {
"name": "John",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"zip": "12345"
},
"hobbies": [
{"name": "reading", "frequency": "weekly"},
{"name": "cycling", "distance": "20km"},
{"name": "hiking", "difficulty": "medium"}
]
}
# Summarize the structure of the modified dictionary
summarize_dict_structure_v3(nested_dict_v3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment