1

I am reading a string from a file in my system. The string is as follows:

A -> B [ label="5.000" ];
B -> A [ label="-5.000" ];

I want to populate a set node and dictionary adj. Here's my code:

node = set()
adj = {}
with open("tiny_stn.dot",'r+t') as demofile:
    lines = demofile.readlines()
    node = {line.split()[0] for line in lines if "->" in line}
    adj = {line.split()[2]:line.split('"')[1] for line in lines if '->' in line}

I want the set to be node={'A','B'} and the dictionary to be adj={'A':{'B': 5.000}, 'B':{'A': -5.000}}

Populating the set works fine. The challenge is to populate a dictionary within a dictionary. The last line of code gives me inner dictionary of desired dictionary i.e. 'B': 5.000 as the first element.

Any help is appreciated.

Mark Adler
  • 101,978
  • 13
  • 118
  • 158
Nishanth Nair
  • 17
  • 1
  • 4
  • Thank you for your time! I have found a way to make it work. I replaced the last line with this: ```adj = {line.split()[0] : {line.split()[2] : line.split('"')[1]} for line in lines if '->' in line}``` – Nishanth Nair Mar 05 '22 at 02:56
  • Not a direct answer but a networkx function exists that reads dot files. https://networkx.org/documentation/stable/reference/generated/networkx.drawing.nx_pydot.read_dot.html – JL Peyret Mar 05 '22 at 04:34

1 Answers1

0

I would not recommend using a dictionary comprehension, as it'd likely be difficult to read.

Given that the lines have a specific schema, I would recommend using a regular expression instead:

import re

node = set()
adj = {}
with open("tiny_stn.dot",'r+t') as demofile:
    lines = demofile.readlines()
    for line in lines:
        result = re.search(r"(.+) -> (.+) \[ label=\"(.+)\" \];", line)
        src, dest, weight = result.groups()
        node.add(src)
        node.add(dest)
        if src not in adj:
            adj[src] = {}
            adj[src][dest] = float(weight)
# Prints {'A': {'B': 5.0}, 'B': {'A': -5.0}}
print(adj)
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
  • I am getting an error for your code: ```AttributeError: 'NoneType' object has no attribute 'groups'``` Error is on line: ```src, dest, weight = result.groups()``` – Nishanth Nair Mar 06 '22 at 01:44
  • Without seeing the full file, I can't say for sure why, but it's probably because you have a line that doesn't follow the structure you've outlined. Just add an `if` guard to make sure that `result` isn't `None` before calling `.groups()`. – BrokenBenchmark Mar 06 '22 at 03:18