Home > database >  How to put data from CVS file into a dictionary to make a graph?
How to put data from CVS file into a dictionary to make a graph?

Time:09-24

I have an issue working with CVS files.

I've been asked to read 2 CVS files and make a graph with said data. lineDefinition.csv shows info as follows:

"station1","station2","line"
11,163,1
11,212,1

stations.csv shows info as follows:

"id","latitude","longitude","name","display_name","zone","total_lines","rail"
1,51.5028,-0.2801,"Acton Town","ActonTown",3,2,0
2,51.5143,-0.0755,"Aldgate",NULL,1,2,0

I want a dictionary in which I have: {"station number": "station connection1", "station connection2", ... , "station connection"n"}

How can I use while/for cycles to grab ONLY the info I need and place it in the dictionary?

lineDefinition.csv has data of all connections between stations, and stations.csv has the name of the stations.

I've tried to read and place the info in dictionaries in the next way using lists and the append function:

import csv
dictgrafo = []
dictestaciones = []
dictline = []

with open('lineDefinition.csv', newline='') as csvFile1:
    for line in csv.DictReader(csvFile1):
        dictgrafo.append(line)
        #print(dictgrafo)

print("---------Graph:---------")
print(dictgrafo)

#Stations
with open('stations.csv', newline='') as csvFile2:
    for line in csv.DictReader(csvFile2):
        dictestaciones.append(line)
        #print(dictgrafo)

print("---------stations:---------")
print(dictestaciones)

CodePudding user response:

This code will create a graph of the stations. Note that a line goes both ways, so you need to make two entries:

import csv
dictgrafo = {}

with open('lineDefinition.csv', newline='') as csvFile1:
    for line in csv.DictReader(csvFile1):
        s1 = int(line['station1'])
        s2 = int(line['station2'])
        if s1 not in dictgrafo:
            dictgrafo[s1] = []
        dictgrafo[s1].append(s2)
        if s2 not in dictgrafo:
            dictgrafo[s2] = []
        dictgrafo[s2].append(s1)
        
print("---------Graph:---------")
print(dictgrafo)

Output:

timr@Tims-NUC:~/src$ python x.py
---------Graph:---------
{11: [123, 22], 123: [11, 9], 22: [11], 33: [10], 10: [33], 9: [123, 16], 16: [9]}
timr@Tims-NUC:~/src$ 
  • Related