0

I have the following dictionary representing id:parent. {1: 2, 3: 1}.

I need to loop and check if id == parent then it is a child.

For example here: 1=1 so 3 is the child of 1.

I will append it to the dictionary accordingly. Any ideas?

 d={1:2, 3:1}
      for node in d:
galfisher
  • 1,122
  • 1
  • 13
  • 24
user3057109
  • 51
  • 1
  • 8

2 Answers2

1
dict1={1:2,2:3,3:1,4:1,5:2}
result={}
for key in dict1.keys():
    result[key]=[]
    for item in dict1.items():
        if key==item[1]:
            result[key].append(item[0])
print(result)  

output:
   {1: [3, 4], 2: [1, 5], 3: [2], 4: [], 5: []}

If you don't want to have those ids with no child, then you can write in the following way.

dict1={1:2,2:3,3:1,4:1,5:2}
result={}
for key in dict1.keys():
    for item in dict1.items():
        if key==item[1]:
            if key not in result:
                result[key]=[]
            result[key].append(item[0])
print(result)
output:
{1: [3, 4], 2: [1, 5], 3: [2]}
Murali
  • 364
  • 2
  • 11
1

An O(n) solution would be:

child_parent = {1:2, 3:1, 4:1, 5:2, 1:5, 6:5, 7:2}
parent_children = {}
for child, parent in child_parent.items():
    parent_children.setdefault(parent, []).append(child)

giving:

{5: [1, 6], 1: [3, 4], 2: [5, 7]}

And, for ease of evaluation, the data represents the following tree:

  2
 / \
7   5
   / \
  6   1
     / \
    3   4
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54