inverting a dictionary of lists

B

bpowah

I searched for an hour and don't see a solution to this (i assume
somewhat common) problem.

I have a very large dictionary of lists:
d = {a:[1,2], b:[2,3], c:[3]}
and i want to reverse the associativity of the integers thusly:
inverse(d) makes {1:[a], 2:[a,b], 3:[b,c]}

my solution expands the original dict into two lists of keys and list
elements:
list1: [a,a,b,b,c]
list2: [1,2,2,3,3]
then recombines them with the reverse operation.

but this takes too much time and a lot of memory.
I wonder if anyone can point me to a more efficient solution?
 
G

Gabriel Genellina

I searched for an hour and don't see a solution to this (i assume
somewhat common) problem.

I have a very large dictionary of lists:
d = {a:[1,2], b:[2,3], c:[3]}
and i want to reverse the associativity of the integers thusly:
inverse(d) makes {1:[a], 2:[a,b], 3:[b,c]}

my solution expands the original dict into two lists of keys and list
elements:
list1: [a,a,b,b,c]
list2: [1,2,2,3,3]
then recombines them with the reverse operation.

but this takes too much time and a lot of memory.
I wonder if anyone can point me to a more efficient solution?

py> d = dict(a=[1,2], b=[2,3], c=[3])
py> result = {}
py> for k,v in d.iteritems():
.... for item in v:
.... result.setdefault(item, []).append(k)
....
py> result
{1: ['a'], 2: ['a', 'b'], 3: ['c', 'b']}
py>

You may use collections.defaultdict too - search some recent posts.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top