Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have the csv file that looks like this:

Material, Property, Temperature, Allowable

EBM,Proof Strength,10,100

EBM,Proof Strength,100,50

EBM,Ultimate Strength,10,200

EBM,Ultimate Strength,120,100

TAK,Proof Strength,20,120

TAK,Proof Strength,150,70

TAK,Ultimate Strength,20,230

TAK,Ultimate Strength,100,130

I need the output like this:

    mat_database = {'TAK':{'Proof Strength':{'Temperature':['C', 20.0, 150.0],  'Allowable':['MPa',120.0, 70.0]},

'Ultimate Strength':{'Temperature':['C', 20.0, 100.0],  'Allowable':['MPa',230.0, 130.0]}},

'EBM':{'Proof Strength':{'Temperature':['C', 10.0, 100.0],  'Allowable':['MPa',100.0, 50.0]},

'Ultimate Strength':{'Temperature':['C', 10.0, 120.0],  'Allowable':['MPa',200.0, 100.0]}}}

I am able to read my csv file using DictReader as shown below:

import os

import csv

SourceDir = ExtAPI.ExtensionManager.CurrentExtension.InstallDir  #Source directory got from Ansys application

    csvfile = "Material_Database.csv"

    fs = os.path.join(SourceDir, csvfile)

    ExtAPI.Log.WriteMessage(str(fs))

    mat_database = {}

    with open(fs, mode = 'r') as csv_file:

        data = csv.DictReader(csv_file, delimiter=",")

        for row in data:

            #code  

    print mat_database

 Can someone please help me with this?

1 Answer

0 votes
by (36.8k points)

You can use the below code:

d = {}

header = True

with open("txt.csv") as f:

    for line in f.readlines():

        if header:

            header = False

            continue

        m, p, t, a = line.strip().split(",")

        d_m = d.get(m,{})

        d_p = d_m.get(p, {})

        d_t = d_p.get('Temperature',['C'])

        d_t.append(float(t))

        d_a = d_p.get('Allowable',['MPa'])

        d_a.append(float(a))

        d_p['Temperature'] = d_t

        d_p['Allowable'] = d_a

        d_m[p] = d_p

        d[m] = d_m

print(d)

Improve your knowledge in data science from scratch using Data science online courses

Browse Categories

...