inverting a dictionary of lists

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • bpowah@gmail.com

    #1

    inverting a dictionary of lists

    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?

  • Gabriel Genellina

    #2
    Re: inverting a dictionary of lists

    En Fri, 15 Jun 2007 00:20:33 -0300, <bpowah@gmail.c omescribió:
    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?
    pyd = dict(a=[1,2], b=[2,3], c=[3])
    pyresult = {}
    pyfor k,v in d.iteritems():
    .... for item in v:
    .... result.setdefau lt(item, []).append(k)
    ....
    pyresult
    {1: ['a'], 2: ['a', 'b'], 3: ['c', 'b']}
    py>

    You may use collections.def aultdict too - search some recent posts.

    --
    Gabriel Genellina

    Comment

    • Raymond Hettinger

      #3
      Re: inverting a dictionary of lists

      On Jun 14, 8:20 pm, bpo...@gmail.co m 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

      Comment

      Working...