def assoc_in(d, ks, v):
    """
    Associates a value in a nested associative structure, where `ks` is a
    sequence of keys and `v` is the new value, and returns a nested structure.
    If any levels do not exist, `dict`s will be created.
    """
    ks_ = ks[:-1]
    last = ks[-1]
    d_ = d
    for k in ks_:
        if k not in d_:
            d_[k] = {}
        d_ = d_[k]
    d_[last] = v
    return d
