0

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.

7
  • What's with the all the stuff after your return statement? Commented Mar 15, 2016 at 16:07
  • 3
    Your oddly-named list2 and your d shouldn't even run: lists aren't hashable, so you can't use them as dictionary keys. Commented Mar 15, 2016 at 16:08
  • @DSM -- That was my first thought too, but If they really are after the return statement, then they don't run (which might explain why some of the tests pass?) Commented Mar 15, 2016 at 16:10
  • Use collections.defaultdict Commented Mar 15, 2016 at 16:10
  • @mgilson you got it! Commented Mar 15, 2016 at 16:10

1 Answer 1

3

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Now it's outputting defaultdict(<type 'list'>, {}) for every test. Any idea why it's doing that? Do i need to add a dict.get?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.