efficiently swap a python dict's keys and values where the values contain one or more elements
Question: Suppose I have a dict:

    
    
    x =  { "a": ["walk", "the", "dog"], "b": ["dog", "spot"], "c":["the", "spot"]  }
    

and want to have the new dict:

    
    
    y = { "walk": ["a"], "the": ["a", "c"], "dog":["a", "b"], "spot":["b","c"]  }
    

What is the most efficient way to do this? If a solution is a few lines and is
somehow made simple by a pythonic construct what is it (even if it's not most
efficient)?

Note that this is different than other questions where the value is a single
element and not a list.


Answer: You can use `defaultdict`:

    
    
    from collections import defaultdict
    
    y = defaultdict(list)
    
    for key, values in x.items():  # .iteritems() in Python 2
        for value in values:
            y[value].append(key)
    

