def map_nested(dd, fn):
    """Map a function to a nested data structure (containing lists or dictionaries

    Args:
      dd: nested data structure
      fn: function to apply to each leaf
    """
    if isinstance(dd, dict):
        return {key: map_nested(dd[key], fn) for key in dd}
    elif isinstance(dd, list):
        return [map_nested(x, fn) for x in dd]
    else:
        return fn(dd)