Tuesday, May 16, 2023

Dictionary with depth and width

 Nice code for creating dict with depth and width


def create_nested_dict(depth, width):

    if depth == 0:

        return {}


    nested_dict = {}

    nested_dict['level'] = depth

    nested_dict['data'] = {}

    

    for i in range(width):

        nested_dict['data'][f'key_{i}'] = create_nested_dict(depth - 1, width)

    

    return nested_dict


# Set the desired depth and width of the nested dictionary

depth = 3

width = 2


# Create the nested dictionary

nested_dict = create_nested_dict(depth, width)


# Print the nested dictionary

import pprint

pprint.pprint(nested_dict)

No comments:

Post a Comment