Search code examples
djangohelper

Do it exist a helper function how data_get (Laravel) in Django?


The data_get function retrieves a value from a nested array or object using "dot" notation:

$data = ['products' => ['desk' => ['price' => 100]]];

$price = data_get($data, 'products.desk.price');

// 100

More detail in Laravel Doc


Solution

  • I do this function:

    def get_data(data, dot_path, default=None):
        arr_paths = dot_path.split('.')
        result = data
    
        for path in arr_paths:
            try:
                if isinstance(result, (dict, list, tuple)):
                    result = result[path]
                else:
                    result = None
            except KeyError as e:
                result = None
    
        if not result:
            result = default
    
    return result