【发布时间】:2016-12-06 16:34:35
【问题描述】:
编写一个函数 parse,它接受一个文件名并使用逗号分隔值格式将每一行解析为字典字典。给出的示例文件是:
id,age,name
100,31,George
101,47,Herbert
103,72,Harriet
预期的输出字典是:
{'103': {'name': 'Harriet', 'age': '72', 'id': '103'}, '100': {'name':
'George', 'age': '31', 'id': '100'}, '101': {'name': 'Herbert', 'age': '47',
'id': '101'}}
确保使用字符串的 .strip() 方法从您解析的每一行中删除行尾字符。
提示:您应该粘贴上一个问题中的 data_dictionary 函数,并从 parse 函数中调用它以帮助处理每一行。
例如:
测试结果
print(sorted(d["100"].items()))= = [('age', '31'), ('id', '100'), ('name', 'George')]
print(sorted(d["101"].items()))= [('age', '47'), ('id', '101'), ('name', 'Herbert')]
print(sorted(d["103"].items())) = [('age', '72'), ('id', '103'), ('name', 'Harriet')]
这是我拥有的代码。 Data_dictionary 是完美的,但需要解析。想不通的请帮忙!
def data_dictionary(keys,values):
d = {}
for i in range(len(keys)):
d[keys[i]] = values[i]
return d
def parse(file):
d = {}
with open(file) as file_name:
for line in file_name:
keys = (item.strip() for item in line.split(','))
for line in file_name:
values = (item.strip() for item in line.split('/n'))
data_dictionary(keys,values)
return d
【问题讨论】:
-
你有
id作为主键,为什么你需要将它添加到字典的正文中? -
为什么有 2 个循环?只需阅读第一行以获取密钥然后循环。
标签: python file parsing dictionary