List of Relational Tuples Into Dictionary

Viewed 81

I have the following list of tuples:

[(0, 1), (1, 2), (1, 3), (3, 4), (5, 6), (4, 6)]

I want the following nested Dictionary:

{
   "0":{
      "1":{
         "2":{},
         "3":{
            "4":{
               "6":{}
            }
         }
      }
   },
   "5":{
      "6":{}
   }
}

What approach should be followed to convert the above list of tuples into a nested dictionary as illustrated above? Basically, I wanted to store the following graph nodes and their relationship as a dictionary.

enter image description here

2 Answers

This is pretty easy with a defaultdict. Just need some extra logic to delete any nodes that aren't top level/ parents in the graph.

from collections import defaultdict

data = [(0, 1), (1, 2), (1, 3), (3, 4), (5, 6), (4, 6)]

result = defaultdict(dict)
children = set()

for parent, child in data:
    result[parent][child] = result[child]
    children.add(child)

for child in children:
    del result[child]

print(dict(result))
{0: {1: {2: {}, 3: {4: {6: {}}}}}, 5: {6: {}}}

You can also use recursion:

data = [(0, 1), (1, 2), (1, 3), (3, 4), (5, 6), (4, 6)]
def to_dict(n):
  return {b:to_dict(b) for a, b in data if a == n}

r = {a:to_dict(a) for a, _ in data if not any(b == a for _, b in data)}

Output:

{0: {1: {2: {}, 3: {4: {6: {}}}}}, 5: {6: {}}}
Related