【问题标题】:Function that reads a file and parses it into dictionary读取文件并将其解析为字典的函数
【发布时间】: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


【解决方案1】:

你正在用生成器表达式做奇怪的事情。这是一个 csv 文件。使用 csv 模块读取。

import csv

def parse(file):
    d = {}
    with open(file) as f:
        r = csv.reader(f)
        _ = next(r) #consume the headers
        for line in r:
            d.update({d[0]: {'age': d[1], 'name':d[2]}})

    return d

或者我们可以使用csv.DictReader

def parse(file):
    d = {}
    with open(file) as f:
        r = csv.DictReader(f)
        for line in r:
            id = line.pop('id')
            d.update({id: line})
    return d

【讨论】:

    猜你喜欢
    • 2016-04-11
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多