将文本文件转换为大字典Python

z8dt9xmd  于 2022-12-01  发布在  Python
关注(0)|答案(3)|浏览(140)

我有一个文本文件,看起来像这样:

subjects ENGLISH, MATHS, SCIENCE

Joe, A, A, B

Dave, A, B, C

Will, D, D, E

我想用Python把它放到字典里

{’Joe’:{’ENGLISH’:A,’MATHS’:A,’SCIENCE’:B},
’Dave’:{’ENGLISH’:A,’MATHS’:B,’SCIENCE’:C},
’Will’:{’ENGLISH’:D,’MATHS’:D,’SCIENCE’:E}}

我如何在一本字典里做这件事?

ct3nt3jp

ct3nt3jp1#

假设您有一个名为file.txt的文件,其中包含以下内容:

subjects ENGLISH, MATHS, SCIENCE

Joe, A, A, B

Dave, A, B, C

Will, D, D, E

尝试使用*解包:

results = {}
with open('file.txt') as file:
    _, *subjects = next(file).split(' ')  # Read header row
    subjects = [s[:-1] for s in subjects]  # Remove trailing comma/newline from subjects
    for line in file:
        if line != '\n':  # Skip empty lines
            name, *grades = line.strip().split(', ')
            results[name] = dict(zip(subjects, grades))
print(results)

您也可以在程式码中定义主旨,并完全略过标题列:

subjects = ['ENGLISH', 'MATHS', 'SCIENCE']
results = {}
with open('file.txt') as file:
    next(file)  # Skip header row since we have defined subjects in code...
    for line in file:
        if line != '\n':  # Skip empty lines
            name, *grades = line.strip().split(', ')
            results[name] = dict(zip(subjects, grades))
print(results)

输出:

{'Joe': {'ENGLISH': 'A', 'MATHS': 'A', 'SCIENCE': 'B'}, 'Dave': {'ENGLISH': 'A', 'MATHS': 'B', 'SCIENCE': 'C'}, 'Will': {'ENGLISH': 'D', 'MATHS': 'D', 'SCIENCE': 'E'}}
mbskvtky

mbskvtky2#

我们可以使用pd.read_csv()读取文件,并使用以下语句将pd转换为字典:df.to_dict('index')

tp5buhyn

tp5buhyn3#

您可以将文本文件转换为CSV

Name, ENGLISH, MATHS, SCIENCE

Joe, A, A, B

Dave, A, B, C

Will, D, D, E

然后使用Pandas的库来读取CSV文件并将其转换成字典。

>>> import pandas as pd
>>> pd.read_csv('file_path.csv',index_col='Name').transpose().to_dict()

{'乔':{'英语':“A”、“数学”:“A”、“科学”:“B”},“戴夫”:{'英文':“A”、“数学”:“B”,“科学”:“C”},“威尔”:{'英文':“D”、“数学”:“D”、“科学”:'E'}}

相关问题