1

So i have the below text as an input file:

A B 1
A C 2
B C 1
B D 3
B E 2
C D 1
C E 2
D E 4
D F 3
E F 3

and i want to store all these values in a nested dictionary in python:

{ 'A': {'B': 1, 'C': 2},
'B': {'C': 1, 'D': 3, 'E': 2},
'C': {'D': 1, 'E': 2},
'D': {'E': 4, 'F': 3},
'E': {'F': 3} }

This is my code which is reading an input file and trying to convert it into a nested dictionary

inputfile = open("input.txt", "r")
lines = inputfile.readlines()
edges = []
for line in lines:
    edges.append(line.split())
d = {}
nn={}

for i in edges:
    nn.update({i[1]:i[2]})
    d[i[0]] = nn
    index+=1

print(d)

This is my incorrect output

{'A': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}, 'B': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}, 'C': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}, 'D': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}, 'E': {'B': '1', 'C': '1', 'D': '1', 'E': '4', 'F': '3'}}

I am looking for a correct if else condition which will update the dict items when the key is same and append if it is different. Thanks in advance.

2 Answers 2

1

You can do:

di={}
with open(fn) as f_in:
    for line in f_in:
        li=line.split()
        di.setdefault(li[0],{})[li[1]]=li[2]

>>> di
{'A': {'B': '1', 'C': '2'}, 'B': {'C': '1', 'D': '3', 'E': '2'}, 'C': {'D': '1', 'E': '2'}, 'D': {'E': '4', 'F': '3'}, 'E': {'F': '3'}}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use recursion with collections.defaultdict:

import collections
def group(d):
  _d = collections.defaultdict(list)
  for a, *b in d:
    _d[a].append(b)
  return {a:group(b) if len(b) > 1 else dict(b) if len(b[0]) > 1 else b[0][0] for a, b in _d.items()}

content = [i.strip('\n').split() for i in open('filename.txt')]
final_result = group(content)

Output:

{'A': {'B': '1', 'C': '2'}, 'B': {'C': '1', 'D': '3', 'E': '2'}, 'C': {'D': '1', 'E': '2'}, 'D': {'E': '4', 'F': '3'}, 'E': {'F': '3'}}

This will also work on larger input samples:

s = """
  A B C D
  A C D E
  A H I F
  B D T G
  B F E H
  B U F A
  """
content = [i.split() for i in filter(None, s.split('\n'))]
print(group(content))

Output:

{'A': {'B': {'C': 'D'}, 'C': {'D': 'E'}, 'H': {'I': 'F'}}, 'B': {'D': {'T': 'G'}, 'F': {'E': 'H'}, 'U': {'F': 'A'}}}

1 Comment

Thank you so much for the quick response and a very informative answer. I am still learning Python basics and this really helped me to understand the concept of recursion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.