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

标签 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
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
我尝试了网上找到的几种嵌套方法。没有一个适合我的目的,或者我错过了一些东西。有人可以帮我解决这个问题吗?

最佳答案

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)

关于python - 如何从给定文件结构的 CSV 文件中读取嵌套字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64566502/

相关文章:

Python:从文本文件中读取字典

python - 在 Python 中,根据字典是否包含键为变量赋值的最小方法是什么?

python - 为什么我的 clojure shell 结果与 python 中的结果不同?

python - 本地主机和 pythonanywhere 上的 OAuth

python - 如何在 python 中创建具有重复键的嵌套字典

python - 更新 RDD pyspark 中的字典值

python - 使用函数值访问 python dict

python - 文件路径中存在反斜杠时意味着什么?

javascript - Flask request.files.getlist 无法循环访问多个文件

python - 我想将所有日志附加到 python 的一个文件中