def validate_doc(doc, mandatory=None, optional=None):
    """Raises error if a dictionary contains labels that are not in the given
    label lists or if there are labels in the mandatory list that are not in
    the dictionary. Returns the given dictionary (if valid).

    Paramaters
    ----------
    doc: dict
        Dictionary serialization of an object
    mandatory: list(string)
        List of mandatory labels for the dictionary serialization
    optional: list(string), optional
        List of optional labels for the dictionary serialization

    Returns
    -------
    dict

    Raises
    ------
    ValueError
    """
    if mandatory is not None:
        for key in mandatory:
            if key not in doc:
                raise ValueError("missing element '{}'".format(key))
    labels = mandatory if mandatory is not None else list()
    if optional is not None:
        labels = labels + optional
    for key in doc:
        if key not in labels:
            raise ValueError("unknown element '{}'".format(key))
    return doc
