首页 > 解决方案 > 文本文件中的嵌套字典,为缺失值返回 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')

任何建议将不胜感激!仍在学习,所以我的代码中可能会有很多错误。

标签: pythoncsvfiledictionary

解决方案


使用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:]:
    ...

推荐阅读