-2

I would like to invert for example this dictionary:

{1: {1: '[]', 2: '[1]'}, 2: {1: '[]', 3: '[1]'}, 3: {1: '[]'}}

Imagine that this is a directed graph with vertices 1, 2, 3 and labelled edges like 1 -> 1 with label '[]', represented in dictionary form by 1: {1: '[]'. The labels don't have to be strings, they can just be lists.

I want to reverse the edges and keep the labels as they are. The output i want is:

{1: {1:'[]', 2:'[]', 3:'[]'}, 2: {1:'[1]'}, 3:{2:'[1]'}}

I saw some methods like Python reverse / invert a mapping but they all work for simpler dictionaries having no "labels".

Community
  • 1
  • 1
bruco
  • 141
  • 1
  • 12
  • 4
    What is the desired output? What have you tried? Dies it work? –  Apr 16 '15 at 17:24
  • 1
    Be little bit more specific what you want as a output. write down the output for the example mentioned by you. – Manjunath N Apr 16 '15 at 17:36
  • Edit: now there is the output I want. I invert the edges of the labelled graph and I keep the labels as before. – bruco Apr 17 '15 at 09:29
  • Shouldn't the output be `{1: {1: '[]', 2: '[]', 3: '[]'}, 2: {1: '[1]'}, 3: {2: '[1]'}}`? Note the `2` in the last sub-dict. – tobias_k Apr 17 '15 at 10:04
  • @tobias_k Completely right! Edited, now it is correct. – bruco Apr 17 '15 at 10:09

1 Answers1

0

Just iterate the sub-dictionaries and the keys in those and add them to a new dictionary with first and second key reversed.

d = {1: {1: '[]', 2: '[1]'}, 2: {1: '[]', 3: '[1]'}, 3: {1: '[]'}}
p = {}
for from_, subdict in d.iteritems():
    for to, value in subdict.iteritems():
        p.setdefault(to, {})
        p[to][from_] = value
print p

Or use a defaultdict, i.e. p = collections.defaultdict(dict), then you don't need the p.setdefault(to, {}) line.

Afterwards, p is {1: {1: '[]', 2: '[]', 3: '[]'}, 2: {1: '[1]'}, 3: {2: '[1]'}}

tobias_k
  • 81,265
  • 12
  • 120
  • 179