I am new to python and stackoverflow. Please be kind. I have a 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 an 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 the 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
I tried several nesting method found online. None suits my purpose or I am missing something. Can someone please help me with this?
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.