ckdanny
2/27/2020 - 2:30 PM

Convert iterable objects' key as path

Convert iterable objects' key as path

def to_path(dictionary: dict or list or tuple):
    """
    This function is used to convert iterable obj ects' key as path

    :param dict or list or tuple dictionary: iterable object containing dict
    :return: iterable object
    """

    def try_iterate(path, d):
        """Try to see if it can continue to move to next layer"""
        if isinstance(d, dict):
            return reduce(lambda master, slave: master + slave,
                          [try_iterate("{}/{}".format(path, k), v) for k, v in d.items()])
        elif isinstance(d, list) or isinstance(d, tuple):
            return list(map(lambda item: "{}/{}".format(path, item), d))
        return ["{}/{}".format(path, d)]

    def to_path_by_level(data):
        """Implement the to path the iterable object"""
        if isinstance(data, dict):
            return reduce(lambda master, slave: master + slave, [try_iterate(k, v) for k, v in data.items()])
        elif isinstance(data, list) or isinstance(data, tuple):
            return list(map(lambda item: to_path_by_level(item), data))
        else:
            return data

    return to_path_by_level(dictionary)