import itertools


def get_mesos_slaves_grouped_by_attribute(slaves, attribute):
    """Returns a dictionary of unique values and the corresponding hosts for a given Mesos attribute

    :param slaves: a list of mesos slaves to group
    :param attribute: an attribute to filter
    :returns: a dictionary of the form {'<attribute_value>': [<list of hosts with attribute=attribute_value>]}
              (response can contain multiple 'attribute_value)
    """
    sorted_slaves = sorted(
        slaves,
        key=lambda slave: slave['attributes'].get(attribute),
    )
    return {
        key: list(group) for key, group in itertools.groupby(
            sorted_slaves,
            key=lambda slave: slave['attributes'].get(attribute),
        ) if key
    }