print nested object in python

To print a nested object in python, such as a dictionary containing other dictionaries, lists, or other objects, you can use a combination of loops and recursion.

Here's a basic example of printing a nested dictionary:

main.py
my_dict = {
    "key1": "value1",
    "key2": {
        "nested_key1": "nested_value1",
        "nested_key2": "nested_value2"
    }
}

def print_nested_dict(dictionary):
    for key, value in dictionary.items():
        if isinstance(value, dict):
            print(key)
            print_nested_dict(value)
        else:
            print(f"{key}: {value}")

print_nested_dict(my_dict)
388 chars
18 lines

This will print out the contents of the dictionary, including any nested dictionaries or other objects.

Output:

main.py
key1: value1
key2
nested_key1: nested_value1
nested_key2: nested_value2
72 chars
5 lines

gistlibby LogSnag