文本文件中的嵌套字典,对于缺失的值返回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,,

我正在尝试制作嵌套字典,名称是键,其余是相应的值。如果文件中缺少任何信息/值,则value应为None。

The result I want
'Abby': {'Job': 'Manager', 'Country’: ‘Berlin', 'Color': 'Green', 'Animal':'Dog'}
'Nayla': {'Job': 'Student', 'Country’: ‘USA', 'Color': None, 'Animal':'Cat'}

既然我解决了索引错误,现在我的问题是如何在"字典的缺失值"中获得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扩展。它们是一种非常常见的文件格式。我通常使用Pandas库来处理CSV文件。

所以,如果你有可能在你的Python环境中安装新的库,我建议安装Pandas,然后这样做:

import pandas as pd

df = pd.read_csv("details.txt")
df.set_index("Name", inplace=True)

然后,如果你想了解某个人的信息,你可以这样做:

df.loc["Abby", :]

您还可以使用Pandas库做许多其他事情,例如进行计算(例如,您的数据集中有多少人拥有"Dog"如Animal?),写入新的CSV文件…

如果您不想安装Pandas,您仍然可以使用csv模块读取文件,该模块是标准库的一部分,因此它已经包含在您的Python安装中。但我个人推荐熊猫,它非常强大!

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

如果您确实不想使用任何外部库(如Pandas或csv),请尝试以下解决方案:

file_name = "details.txt"
with open(file_name, "r") as f:
lines = f.readlines()
lines = [line.rstrip() for line in lines]
columns = lines[0].split(",")

def parse_sub_dict(columns, raw_values):
values = raw_values.split(",")

sub_dict = {}
for column, value in zip(columns, values):
if value == "":
value = None

sub_dict[column] =  value

return sub_dict
list_dicts = [parse_sub_dict(columns, line) for line in lines[1:]]
nested_dict = {sub_dict.pop("Name"): sub_dict for sub_dict in list_dicts}

正如其他人在评论中指出的那样,这里有一个"错误"。在你发布的文件中:有一个多余的";在最后一行。我的解决方案解决了parse_sub_dict函数中的问题,其中zip(columns,values)返回columns长度的迭代器,这是您的第一行。

最新更新