def add_group_to_grouping(state_collection, grouping_name, group, group_key=None):
    """
    Adds a group to the named grouping, with a given group key

    If no group key is given, the lowest available integer becomes the group key

    If no grouping exists by the given name a new one will be created

    Replaces any group with the same grouping_name and the same group_key
    """
    if state_collection.groupings.get(grouping_name) is None:
        state_collection.groupings[grouping_name]= {}
    if group_key is None:
        group_key= _next_lowest_integer(state_collection.groupings[grouping_name].keys())
    state_collection.groupings[grouping_name][group_key]= group
    return state_collection
Adds a group to the named grouping, with a given group key

    If no group key is given, the lowest available integer becomes the group key

    If no grouping exists by the given name a new one will be created

    Replaces any group with the same grouping_name and the same group_key