简体   繁体   中英

How to exclude repeated keys in dictionary of dictionaries when reading a csv file?

I have made a code so far that reads a csv file and returns the data in the form of nested dictionaries. The first column of the table in the csv file holds the keys and its keys values are the values of the same row.

I want to transform my code so it can exclude a key and its values if it is subsequently repeated in this column with the same string name. For example, if I have twice the string "Name" in a column I want to exclude the first "Name" as a key field and replace it (along with all its values) by the subsequent "Name" which may be some lines after.

My code so far:

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

Maybe you are looking for something like this:

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'))

The output is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM