4

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?

4
  • 1
    Your desired output is not valid Python. Commented Oct 28, 2020 at 4:39
  • How do you get the units (MPa, C)? Do you just put them in by hand? Commented Oct 28, 2020 at 4:40
  • Thanks Mark, There are some missing braces in output of my original post which I have corrected now. Commented Oct 28, 2020 at 4:44
  • Yes, in the Temperature and Allowable lists I always need first entry to be 'C' and 'MPa' respectively. Commented Oct 28, 2020 at 4:45

1 Answer 1

2
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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.