from functools import reduce
import operator
import collections


def strings_to_wordsets(strings, stop_words=None):
    """Build a dict of wordsets from a list of strings, with optional filter.

    For each distinct word found in the list of strings, the wordset dict will
    map that word to a set of the strings that contain it. A list of words to
    ignore may be passed in stop_words.

    """
    string_words = [set(w.split(' ')) for w in (s.lower() for s in strings)]
    words = reduce(operator.or_, string_words)
    if stop_words:
        words -= set(stop_words)
    wordsets = collections.OrderedDict(
        (w, set(strings[i] for i, s in enumerate(string_words) if w in s))
        for w in sorted(words))
    return wordsets