Python inverted dictionaries
Question: I'm currently writing a function that takes a dictionary with immutable values
and returns an inverted dictionary. So far, my code is getting extremely
simple tests right, but it still has some kinks to work out

    
    
    def dict_invert(d):
    
         inv_map = {v: k for k, v in d.items()}
    
         return inv_map
    
         list1 = [1,2,3,4,5,6,7,8]
         list2 = {[1]:3245,[2]:4356,[3]:6578}
         d = {['a']:[],['b']:[]}
         d['a'].append(list1)
         d['b'].append(list2)
    

How do I fix my code so that it passes the test cases?

My only thoughts are to change list 2 to `[1:32, 2:43, 3:54, 4:65]`; however,
I would still have a problem with having the `"[]"` in the right spot. I have
no idea how to do that.


Answer: The trick is to realize that multiple keys can have the same values, so when
inverting, you must make sure your values map to a list of keys.

    
    
    from collections import defaultdict
    
    def dict_invert(d):
      inv_map = defaultdict(list)
      for k, v in d.items():
        inv_map[v].append(k)
      return inv_map
    

**EDIT:**

Just adding a bit of more helpful info...

The `defaultdict(list)` makes the default value of the dict = `list()` when
accessed via `[]` or `get` (when normally it would raise `KeyError` or return
`None` respectively).

With that defaultdict in place, you can use a bit of logic to group keys
together... here's an example to illustrate (from my comment above)

Original dict: K0 -> V0, K1 -> V0, K2 -> V0

Should invert to: V0 -> [K0, K1, K2]

**EDIT 2:**

Your tests seem to be forcing you into using a normal dict, in which case...

    
    
    def dict_invert(d):
        inv_map = {}
        for k, v in d.items():
            if v not in inv_map: 
                inv_map[v] = []
            inv_map[v].append(k)
         return inv_map
    

