Skip to content

Instantly share code, notes, and snippets.

@DocMinus
Created August 22, 2024 09:14
Show Gist options
  • Save DocMinus/d787b869ff7bfc31043a9e6750cf0c63 to your computer and use it in GitHub Desktop.
Save DocMinus/d787b869ff7bfc31043a9e6750cf0c63 to your computer and use it in GitHub Desktop.
Analyze unknown nested structure (e.g. list of dictionary of whatever...). In Python
from typing import Dict, List, Set, Tuple, Union
import json
def analyze_nested_structure(
variable: Union[List, Dict, Tuple, Set], indent: int = 0
) -> None:
"""
A generic (recursive) function to analyze the structure of a nested list, dictionary, tuple, or set.
comment out the recursive call to avoid printing large content as required.
"""
indent_str = " " * indent
if isinstance(variable, dict):
print(f"{indent_str}Dictionary with {len(variable)} keys:")
for key, value in variable.items():
print(f"{indent_str} Key: {key}")
# analyze_nested_structure(value, indent + 4)
elif isinstance(variable, list):
print(f"{indent_str}List with {len(variable)} elements:")
for index, element in enumerate(variable):
print(f"{indent_str} Index: {index}")
analyze_nested_structure(element, indent + 4)
elif isinstance(variable, tuple):
print(f"{indent_str}Tuple with {len(variable)} elements:")
for index, element in enumerate(variable):
print(f"{indent_str} Index: {index}")
analyze_nested_structure(element, indent + 4)
elif isinstance(variable, set):
print(f"{indent_str}Set with {len(variable)} elements:")
for element in variable:
print(f"{indent_str} Element: {element}")
analyze_nested_structure(element, indent + 4)
else:
print(f"{indent_str}{type(variable).__name__}: {variable}")
def main():
# data from e.g. a json file
json_file = "myjsonfile.json"
with open(json_file, "r") as f:
data = json.load(f)
analyze_nested_structure(data)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment