python - 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 函数时,它不会附加到字典中,我该如何解决?
解决方案
我已将您的代码修改为以下内容。
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','性别':'男'}}
推荐阅读
- python - 如何避免 Python 用科学计数法打印数字?
- c++ - 如何用 getaddrinfo 替换 inet_pton
- angular - @ngrx/data - 如何扩展集合缩减器/替换对数据服务调用结果的处理?
- ios - 从另一个视图控制器返回时 UIScrollview 不起作用(弹出后)
- javascript - 如果该 div 不包含文本,而是包含浮动 HTML 元素,如何将行号添加到 div 以使其看起来像 IDE 编辑器?
- java - 参数化测试因 mvn test 失败
- javascript - javascript过滤方法不返回一个结果
- kubernetes - 在 Kubernetes 集群上缺少共识的实际后果?
- javascript - node.js SyntaxError:无效或意外的令牌
- python-3.x - 将类实例存储在 python 列表中