首页 > 解决方案 > python上的嵌套字典?

问题描述

我有一个包含姓名、年龄和性别的文本文件。

John, 55, Male
Toney, 23, Male
Karin, 42, Female
Cathie, 29, Female
Rosalba, 12, Female
Nina, 50, Female
Burton, 16, Male
Joey, 90, Male

现在我想做一个 def read_person_data(persons): 可以将信息作为嵌套字典返回。例如,键 'John' 具有字典 {'Age': 55, 'Gender': 'Male'} 作为值。主字典中的键应该是不带逗号的名称,所以我必须做剥离还是?

我尝试过这段代码:

with open('persons.txt','r') as infile:
    dic=[]
    for line in infile:
        s=line.split()
        dic.append(s[0])
    dictofnames={i : s[1] for i in dic}       
    
print(dictofnames)

先列出一个列表,然后把它变成字典,但我每个名字的年龄都错了,不明白如何在名字和年龄后面加上 ,gender: 'male'??但它必须是字典,而不是特定名称的键上格式为 {'Age': 55, 'Gender': 'Male'} 的列表。另外,当我执行 def 函数时,它不会附加到字典中,我该如何解决?

标签: pythondictionarytextnested-lists

解决方案


我已将您的代码修改为以下内容。

    import re
    with open('persons.txt','r') as infile:
        dic={}
        for line in infile:
            s=re.split(', |\n',line)
            dic[s[0]] = {}
            dic[s[0]]['Age'] = s[1]
            dic[s[0]]['Gender'] = s[2]       
    print(dic)

输出: {'John': {'Age': '55', 'Gender': 'Male'}, 'Toney': {'Age': '23', 'Gender': 'Male'}, 'Karin' :{'Age':'42','Gender':'Female'},'Cathie':{'Age':'29','Gender':'Female'},'Rosalba':{'Age': '12', 'Gender': 'Female'}, 'Nina': {'Age': '50', 'Gender': 'Female'}, 'Burton': {'Age': '16', 'Gender ':'男'},'乔伊':{'年龄':'90','性别':'男'}}


推荐阅读