【问题标题】:How to exclude repeated keys in dictionary of dictionaries when reading a csv file?读取csv文件时如何排除字典字典中的重复键?
【发布时间】:2018-12-09 03:02:06
【问题描述】:

到目前为止,我已经编写了一个代码,它可以读取一个 csv 文件并以嵌套字典的形式返回数据。 csv 文件中表的第一列包含键,其键值是同一行的值。

我想转换我的代码,以便它可以排除一个键及其值,如果它随后在此列中以相同的字符串名称重复。例如,如果我在一列中有两个字符串“Name”,我想排除第一个“Name”作为关键字段,并用随后的“Name”替换它(连同它的所有值),这可能是后面的几行.

到目前为止我的代码:

def dict_of_dicts (filename, keyfield):
    tabledict= {}
    with open (filename, "rt", newline='') as csv_file:
        csvreader=csv.DictReader(csv_file, skipinitialspace=True)
        for row in csvreader:
            tabledict[row[keyfield]]=row
    return tabledict

【问题讨论】:

  • 请向我们展示一些示例输入和输出。
  • 亚历克斯所说的。您的描述有点混乱和模棱两可。如果我们能看到一小部分输入和相关的输出,事情就会变得更加清晰。

标签: python csv dictionary


【解决方案1】:

也许你正在寻找这样的东西:

import csv

# implementation following

def dict_of_dicts (filename, keyfield):
    tabledict = {}
    with open(filename, 'rt', newline='') as csv_file:
        csvreader = csv.reader(csv_file, skipinitialspace=True)
        for row in csvreader:
            if len(row) < 1:
                continue
            tabledict[row[0]] = row[1:]
    return tabledict

# example following

with open('test.csv', 'w') as fd:
    w = csv.writer(fd)
    w.writerows([
        ["Name","Andrew","John","Mike"],
        ["Age","20","25","26"],
        ["Weight","65","76","80"],
        ["Height","1.75","1.8","1","9"],
        ["Age","21","26","27"]
    ])

print(dict_of_dicts('test.csv', 'Name'))

输出是:

{'Name': ['Andrew', 'John', 'Mike'], 'Age': ['21', '26', '27'], 'Weight': ['65', '76', '80'], 'Height': ['1.75', '1.8', '1', '9']}

【讨论】:

    猜你喜欢
    • 2021-08-20
    • 1970-01-01
    • 2021-12-24
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    • 2021-05-14
    • 1970-01-01
    相关资源
    最近更新 更多