Home > front end >  Custom function reading data from pajek file and saving into a python dictionary
Custom function reading data from pajek file and saving into a python dictionary

Time:12-09

everyone!

I am currently working on the following task:
"Write a function that will read data from a pajek .net file and save it into a dictionary."

Data written in "pajek.net" file is:

*Vertices 5  
1 "x"  
2 "y"  
3 "z"  
4 "m"  
5 "n"   
*Arcs  
1 2 3  
1 3 5  
2 3 4  
2 5 2  
3 4 1  
4 5 3  

The function I've written goes like this:

def read(pajek):

    list1 = []
    vertices = []
    arcs = []
    edges = []
    
    with open(pajek, 'r') as file:

        lines = file.readlines()
        isStar = ""

        for line in lines:
            if "*" in line:
                isStar = line #in other files I'm working on, there is only a "*" in some lines
            elif isStar.find("*Vertices") != -1:
                vertices.append(line.split())
            elif isStar.find("*Arcs") != -1:
                arcs.append(line.split())
            elif isStar.find("*Edges") != -1:
                edges.append(line.split())

    return vertices, arcs, edges

The next part ("...save it into a dictionary.") is giving me trouble.
I've tried, but there's always some error...

Can someone help me with this?
Also, I must not use imports and modules!

P.S.
I'm fairly new in Python, therefore I'm still learning Python-specific tips and tricks

EDIT: list => list1

CodePudding user response:

In your main add this code to create a dict from the ouput of the read function:

vertices, arcs, edges = read("pajek.net")
result = {"vertices": vertices,"arcs": arcs,"edges": edges}
print(result)

And the result will like that :

{
   "vertices":[
      [
         "1",
         "x"
      ],
   ],
   "arcs":[
      [
         "1",
         "2",
         "3"
      ],
   ],
   "edges":[
      
   ]
}
  • Related