Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extracting a graph from a text file to a python graph

I have a text file with the following graph inside:

1: 2 3 4 5 6 2
2: 3 -4
3: 8 4
4: 5 6
5: 4 -3 8 8
6: 7 3
7: 6 -6 8 7
8:

I’ve been trying to extract this graph into a python graph that is formatted like the example below:

graph = {
        '1': {'2': 3, '4': 5, '6': 2},
        '2': {'3': -4},
        '3': {'8': 4},
        '4': {'5': 6},
        '5': {'4': -3, '8': 8},
        '6': {'7': 3},
        '7': {'6': -6, '8': 7},
        '8': {}
    }

I am new to python and cannot figure it out. I’ve tried using the code below, but it just loads the graph into an array. I am unsure of how to form it into the graph example above.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

graph = []                                 
    with open(fileName,'r') as file:           
        for line in file:                      
            for line in line[:-1].split():  
                    graph.append(line)          

output of above code:

['1:', '2', '3', '4', '5', '6', '2', '2:', '3', '-4', '3:', '8', '4', '4:', '5', '6', '5:', '4', '-3', '8', '8', '6:', '7', '3', '7:', '6', '-6', '8', '7', '8:']

>Solution :

Try storing a variable and slicing every other value in the lines to create the key – value pairs to construct the dictionary, if there is nothing after the colon, it feeds and empty dictionary:

graph = []
with open(fileName,'r') as file:           
    for line in file:                      
        graph.append({line.split(':')[0].replace(' ', ''): (dict(zip(line.split(': ')[1].split()[::2], map(int, line.split(': ')[1].split()[1::2]))) if ': ' in line else {})})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading