def add_main_category(row, categories_dict):
    """
    Add the item's main category to the row
    :param row: A dict containing metadata for one item
    :param categories_dict: A dict mapping subcategories to main categories, as
    a Spark broadcast variable
    :return: A dict containing the original data plus the item's main category
    """
    def get_main_category(categories):
        """
        Given a list of lists of categories returns the main category in that list
        :param categories: A list of lists of categories
        :return: The main category within the ones received as argument, or
        empty string if no such category could be found
        """
        # flaten a list of lists
        flat = set(sum(categories, []))

        # map category names, trim None
        main_categories = list(filter(None, map(categories_dict.value.get, flat)))

        # return the first category, if exists
        if len(main_categories) > 0:
            return main_categories[0]
        else:
            return ''

    if ('categories' not in row) or (not row['categories']):
        row['main_category'] = ''
        row['categories'] = []
    else:
        row['main_category'] = get_main_category(row['categories'])

    return row