from collections import defaultdict
from fnmatch import fnmatch


def groupkeys(keys, patterns):
    """Groups the given set of keys using the given patterns.
    It runs through the patterns sequentially, removing those from keys.
    Returns a dict with {pattern: [matching keys]}.
    Unmatches keys are added with None as the key."""
    ret = defaultdict(list)
    for k in keys:
        matched = 0
        for p in patterns:
            if fnmatch(k, p):
                ret[p].append(k)
                matched = 1
                break
        if not matched:
            ret[None].append(k)
    return dict(**ret)