inverting a dictionary of lists

Raymond Hettinger python at rcn.com
Fri Jun 15 05:52:37 CEST 2007


On Jun 14, 8:20 pm, bpo... at gmail.com wrote:
> 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]}



Try using setdefault:

>>> d = {'a':[1,2], 'b':[2,3], 'c':[3]}
>>> r = {}
>>> for k in d:
	for e in d[k]:
		r.setdefault(e, []).append(k)

>>> r
{1: ['a'], 2: ['a', 'b'], 3: ['c', 'b']}


Raymond




More information about the Python-list mailing list