from typing import Union
from typing import List
from typing import Any


def mutget(d: dict, keys: Union[List, Any], value=None):
    """Returns the value in a nested dictionary, setting anything undefined to
    new dictionaries except for the last one, which is set to the provided value
    if undefined. Like dict.get(), but mutates the original dictionary and can
    handle nested dictionaries/arrays.
    Arguments:
    - d -- dictionary
    - keys -- a single key or a list of keys
    - value (optional) -- default value to use if not present
    Examples:
    my_dict = {'a': {}}
    ensure_dict(my_dict, ['a', 'b', 'c'], 4)
    # The return value is 4.
    # my_dict is now {'a': {'b': {'c': 4}}.
    my_dict = {'a': {'b': {'c': 17}}}
    ensure_dict(my_dict, ['a', 'b', 'c'], 4)
    # The return value is 17.
    # my_dict does not change.
    """
    if not keys:
        return d
    if not isinstance(keys, list):
        keys = [keys]
    for key in keys[:-1]:
        if key not in d:
            d[key] = {}
        d = d[key]
    if keys[-1] not in d:
        d[keys[-1]] = value
    return d[keys[-1]]