Nishanth Nair
Nishanth Nair

Reputation: 17

Trying to populate a dictionary within a dictionary

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.

Upvotes: 1

Views: 98

Answers (1)

BrokenBenchmark
BrokenBenchmark

Reputation: 19223

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)

Upvotes: 0

Related Questions