Python 从文件创建包含列表的嵌套dict

Python 从文件创建包含列表的嵌套dict,python,list,dictionary,txt,Python,List,Dictionary,Txt,例如,对于 Math, Calculus, 5 Math, Vector, 3 Language, English, 4 Language, Spanish, 4 进入字典: data={'Math':{'name':[Calculus, Vector], 'score':[5,3]}, 'Language':{'name':[English, Spanish], 'score':[4,4]}} 我很难在较小的dict中添加值来创建列表。我对这一点非常陌生,我不理解导入命令。非常感谢你的

例如,对于

Math, Calculus, 5 
Math, Vector, 3
Language, English, 4
Language, Spanish, 4
进入字典:

 data={'Math':{'name':[Calculus, Vector], 'score':[5,3]}, 'Language':{'name':[English, Spanish], 'score':[4,4]}}

我很难在较小的dict中添加值来创建列表。我对这一点非常陌生,我不理解导入命令。非常感谢你的帮助

对于每行,找到3个值,然后将它们添加到dict结构中

from pathlib import Path

result = {}
for row in Path("test.txt").read_text().splitlines():
    subject_type, subject, score = row.split(", ")

    if subject_type not in result:
        result[subject_type] = {'name': [], 'score': []}

    result[subject_type]['name'].append(subject)
    result[subject_type]['score'].append(int(score))

您可以通过使用
defaultdict
来简化它,如果密钥还不存在,它将创建映射

result = defaultdict(lambda: {'name': [], 'score': []}) # from collections import defaultdict
for row in Path("test.txt").read_text().splitlines():
    subject_type, subject, score = row.split(", ")
    result[subject_type]['name'].append(subject)
    result[subject_type]['score'].append(int(score))

使用pandas.DataFrame可以直接生成格式化数据并输出所需格式

import pandas as pd

df = pd.read_csv("test.txt", sep=", ", engine="python", names=['key', 'name', 'score'])
df = df.groupby('key').agg(list)
result = df.to_dict(orient='index')
根据您的数据:

data={'Math':{'name':['Calculus', 'Vector'], 'score':[5,3]}, 
      'Language':{'name':['English', 'Spanish'], 'score':[4,4]}}
如果要附加到词典中的列表,可以执行以下操作:

data['Math']['name'].append('Algebra')

data['Math']['score'].append(4)
data['Science'] = {'name':['Chemisty', 'Biology'], 'score':[2,3]}
如果要添加新词典,可以执行以下操作:

data['Math']['name'].append('Algebra')

data['Math']['score'].append(4)
data['Science'] = {'name':['Chemisty', 'Biology'], 'score':[2,3]}

我不确定这是否是你想要的,但我希望它能帮助你

输入文件是否只能使用逗号或空格作为分隔符,而不能同时使用两者?或者,您是否100%确定将始终使用逗号+空格作为分隔符?您可能会考虑奖励那些帮助过您的人,或者至少发表评论来解释缺少的内容;)谢谢你的帮助!您能推荐一些不需要导入命令的其他方法吗?@mylearning第一种方法实际上并不需要,您可以在不使用pahtlib.Path的情况下读取文件。此外,如果不使用库,您也不能期望使用python编写代码,这就是python的强大功能