pythoncsvdictionaryfilereader

Create a dictionary from a csv file with rows


I'm have a csv file

id,name,surname,age
"1, Johny, Black, 25"
"2, Armando, White, 18" 
"3, Jack, Brown, ''"
"4, Ronn, Davidson, ''"
"5, Bill, Loney, 35"

first row this is list, other rows How i can be converted this csv in dictionary. With future filter and sort

import csv
dicts = list()
with open("test.csv", "r", encoding="utf-8") as file:
    csv_reader = csv.reader(file)
    field_list = list()
    record_list = list()
    line_counter = 0
    for row in csv_reader:
        if line_counter == 0:
            field_list = row
            line_counter += 1
        else:
            records = row[0].split(',')
            record_list.append(records)

counter = 0
full = dict()
for record in record_list:
    for field in field_list:
        try:
            if field in full.keys():
                full[field].append(record[counter])
                counter += 1
            else:
                full[field] = [record[counter]]

            if counter == len(record):
                break

        except Exception as e:
            pass

 print(full)

My code convert only 2 rows. I'm try split rows, but this don't help me. Documentation csv lib not help me. Maybe someone knows solution


Solution

  • You never reset your counter to zero, the first time you loop through your nested for loop, the code initializes the dictionary keys to the first row in record_list and the counter remains equal to 0 (therefore only placing the first value in). The second time, the counter increments up to 4. So that every following time, the counter is out of index range for the record, and your exception will be raised.

    I think the second half of your code should look like this:

    full = dict()
    for record in record_list:
        counter = 0
        for field in field_list:
            try:
                if field in full.keys():
                    full[field].append(record[counter])
                else:
                    full[field] = [record[counter]]
                counter += 1
    
            except Exception as e:
                pass
    
     print(full)