python - 文本文件中的嵌套字典,为缺失值返回 None
问题描述
我有一个文本文件 details.txt,其中包含如下数据
Name,Job,Country,Color,Animal
Abby,Manager,Berlin,Green,Dog
Amy, Pianist, Korea,Red,Cat
Jhones,Designer,Australia,Black,Dog
Nayla,Student,USA,,Cat
Oly,Singer,Canada,Blue,,
我正在尝试制作嵌套字典,名称是键,其余是对应的值。如果文件中缺少任何信息/值,则值应为无。
The result I want
'Abby': {'Job': 'Manager', 'Country’: ‘Berlin', 'Color': 'Green', 'Animal':'Dog'}
'Nayla': {'Job': 'Student', 'Country’: ‘USA', 'Color': None, 'Animal':'Cat'}
因为我解决了索引错误,现在我的 Qs 是如何在字典的“缺失值”中获取 None
def nested_dict(x):
d = {}
with open(x,'r') as file1:
lines = file1.readlines()
for w in lines:
words = w.rstrip().split(',')
if words[0] not in d:
d[words[0]] = {'Job': words[1], 'Country': words[2] 'Color': words[3], 'Animal':words[4]}
return d
nested_dict('details.txt')
任何建议将不胜感激!仍在学习,所以我的代码中可能会有很多错误。
解决方案
使用csv
模块和csv.DictReader
. 然后您可以执行以下操作:
import csv
with open("example.csv") as f:
reader = csv.DictReader(f)
result = {d.pop("Name"):d for d in reader}
但是在您的示例中,要从第二行开始,只需执行以下操作:
for w in lines[1:]:
...
推荐阅读
- python - 安装本地 Python 包后 Juypter 笔记本中的 ModuleNotFoundError
- r - 添加数据点以平滑 GPS 坐标
- firebase - Firebase 托管错误 - 添加了一个新域并添加了 A 记录,但我已经等待了 24 小时
- spring-security - 记录 org.springframework
- javascript - 滑动滑块滚动条 - 没有滚动
- php - 视频架构和 Wordpress
- mysql - 1286 - 迁移到 MySQL 时出现未知的存储引擎“MongoDB”
- mysql - 如何从 MySQL 中的存储过程返回字符串值?
- anylogic - SEIZE BLOCK 和优先级
- kotlin - 未调用扩展函数的模拟版本