Blue Monday Blue Monday - 1 year ago 65
Python Question

How do you merge and switch keys with values if they have same values?

Let's say I have a dictionary with these keys and values :

{'foo': 1, 'bar': 5,'foo1' : 1,'bar1' : 1,'foo2': 5}

I can't zip them like this


because this happens :

{1: 'foo', 5: 'bar'}

What I would like to be my output is :


Answer Source

You can't have multiple values for a given key, so the values in such a data structure need to be lists. You can't do this transformation easily with zip(); you'll need a for loop:

my = {'foo': 1, 'bar': 5, 'foo1': 1, 'bar1': 1,'foo2': 5}
rev = {}

for k, v in my.items():
    rev.setdefault(v, []).append(k)

From the edits in your question, it appears that you want to use a set for the values. This is also straightforward:

for k, v in my.items():
    rev.setdefault(v, set()).add(k)

You can also use a defaultdict as Daniel has suggested, but it seems overkill here to do an import just for that. Depending on the size of your dictionary it might be a little faster, since using setdefault() we are continuously creating and throwing away empty containers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download