I want Python to load CSV files in Dict and list types

Asked 2 years ago, Updated 2 years ago, 305 views

As I am a beginner at Python, please let me know if this is a rude question.

I'm thinking about how Python can read data from the following csv files:

CSV

ACDT
1,7 0 0 2
2,7 0 0 3
3,7 0 0 5
4,7 0 0 2
5,7 0 0 3
6,7 0 0 5
0,1 8 10 2
0,2 70 15 3
0,3 9 10 5
0,5 5 10 2
1,2 10 15 3
1,3 90 10 5
2,3 120 10 2
2,4 85 15 3
3,4 7 15 5
5,4 150 15 2
5,6 11 15 3
6,2 140 15 5
6,4 130 15 2

Enter a description of the image here

My goal is to have it read as shown in the image above.
I tried to read columns from the CSV file with only the first row listed, the first row tuple and the second row Dict, the first row tuple and the third row Dict, and the first row tuple and the fourth row Dict, but it didn't work.

Python

import csv

A = [ ]
C = {}
D = {}
T = {}

with open('/Users/data.csv') asf:
    r=csv.reader(f)
    next(r)
    A = [tuple(map(int,line)) for line in r]

    reader=csv.DictReader(f,delimiter='')
    For row in reader:
        C[tuple([int(s) for sin row[1].split(',')]] = int(row['C')]
        D[tuple([int(s) for sin row[1].split(',')]] = int(row['D')]
        T[tuple([int(s) for sin row[1].split(',')]] = int(row['T')]

CSV files are separated by commas and spaces.
I am not particular about anything other than commas, and I would appreciate it if you could let me know if this is easier to use.

python python3 csv

2022-09-30 21:54

2 Answers

Code for ACDT based on the code provided

import csv

A = [ ]
C = {}
D = {}
T = {}

with open('/Users/data.csv') asf:
    r=csv.reader(f,delimiter='')
    next(r)
    For line in r:
        key=tuple(map(int, (val for val inline[0].split(', ')))))))
        A+=[key]
        C[key] = int(line[1])
        D[key] = int(line[2])
        T[key] = int(line[3])


2022-09-30 21:54

Here's how to use pandas:

>>import pandas as pd
>>df=pd.read_csv ('data.csv', engine='python', sep='[,]', skiprows=1, header=None)
>>>A=list(zip(df[0], df[1]))
>>>C,D,T = [dict(zip(A,df[i])) for i in range(2,df.shape[1])]

>>> from print import print
>>pprint(A)
[(1, 7),
 (2, 7),
 (3, 7),
 (4, 7),
 (5, 7),
 (6, 7),
      :

>>pprint(C, sort_dictts=False)
{(1, 7): 0,
 (2, 7): 0,
 (3, 7): 0,
 (4, 7): 0,
 (5, 7): 0,
 (6, 7): 0,
 (0, 1): 8,
 (0, 2): 70,
 (0, 3): 9,
 (0, 5): 5,
      :

>>pprint(D, sort_dictts=False)
{(1, 7): 0,
 (2, 7): 0,
 (3, 7): 0,
 (4, 7): 0,
 (5, 7): 0,
 (6, 7): 0,
 (0, 1): 10,
 (0, 2): 15,
 (0, 3): 10,
 (0, 5): 10,
      :

>>pprint(T, sort_dictts=False)
{(1, 7): 2,
 (2, 7): 3,
 (3, 7): 5,
 (4, 7): 2,
 (5, 7): 3,
 (6, 7): 5,
 (0, 1): 2,
 (0, 2): 3,
 (0, 3): 5,
 (0, 5): 2,
      :


2022-09-30 21:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.