Python 如何从给定文件结构的CSV文件中读取嵌套字典?

Python 如何从给定文件结构的CSV文件中读取嵌套字典?,python,dictionary,Python,Dictionary,我不熟悉python和stackoverflow。请善待我。我有一个csv文件,如下所示: 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 T

我不熟悉python和stackoverflow。请善待我。我有一个csv文件,如下所示:

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
    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]}}}
我需要这样的输出:

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
    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]}}}
我能够使用DictReader读取csv文件,如下所示:

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

我尝试了网上找到的几种嵌套方法。没有一个适合我的目的,或者我错过了什么。有人能帮我一下吗?

您想要的输出不是有效的Python。如何获得单位(MPa,C)?你是手工输入的吗?谢谢马克,我原来的帖子输出中有一些括号缺失,我现在已经更正了。是的,在温度和允许值列表中,我总是需要第一个条目分别是“C”和“MPa”。
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)