从文件创建包含列表的嵌套字典

Create a nested dict containing list from a file

例如

的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]}}

我在附加值以在较小的字典中创建列表时遇到问题。我对此很陌生,我不明白导入命令。非常感谢您的帮助!

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

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]}

我不确定这是否是您想要的,但希望对您有所帮助!