import itertools


def scrape_options_and_index_by_dest(*parsers_and_groups):
    """Scrapes ``optparse`` options from :py:class:`OptionParser` and :py:class:`OptionGroup` objects and builds a dictionary of ``dest_var: [option1, option2, ...]``. This function primarily exists to serve :py:func:`scrape_options_into_new_groups`.

    An example return value: ``{'verbose': [<verbose_on_option>, <verbose_off_option>], 'files': [<file_append_option>]}``

    :type parsers_and_groups: :py:class:`OptionParser` or :py:class`OptionGroup`
    :param parsers_and_groups: Parsers and groups to scrape option objects from

    :return: dict of the form ``{dest_var: [option1, option2, ...], ...}``
    """

    # Scrape options from MRJob and index them by dest
    all_options = {}
    job_option_lists = [g.option_list for g in parsers_and_groups]
    for option in itertools.chain(*job_option_lists):
        other_options = all_options.get(option.dest, [])
        other_options.append(option)
        all_options[option.dest] = other_options
    return all_options