def flatten_dict(data, parent_key='', sep='_'):
    """Flatten a nested dictionary.

    :param data: A nested dictionary
    :type data: dict or MutableMapping
    :param str parent_key: The parent's key. This is a value for tail recursion, so don't set it yourself.
    :param str sep: The separator used between dictionary levels
    :rtype: dict

    .. seealso:: http://stackoverflow.com/a/6027615
    """
    items = {}

    for key, value in data.items():
        # prepend the parent key
        key = parent_key + sep + key if parent_key else key

        if isinstance(value, (dict, MutableMapping)):
            items.update(flatten_dict(value, key, sep=sep))
        elif isinstance(value, (set, list)):
            items[key] = ','.join(value)
        else:
            items[key] = value

    return items
Flatten a nested dictionary.

    :param data: A nested dictionary
    :type data: dict or MutableMapping
    :param str parent_key: The parent's key. This is a value for tail recursion, so don't set it yourself.
    :param str sep: The separator used between dictionary levels
    :rtype: dict

    .. seealso:: http://stackoverflow.com/a/6027615