Reading a csv file as a dictionary with Python (2023-10-01 09:55:53)

Unlike the previous post where dictionaries were stored in csv file with Python, now we want to read the information of a csv file and put it inside the dictionary and if necessary edit them and save them again in csv file format or part of Use them as input for newer codes.

این چیه؟

For this, it is enough to assume that we have the "Cities.csv" file from the previous post and we want to put its information in a list named data that contains the record dictionary. It should be noted that line 5 of the code is used to read the title line.

 

import csv

with open('Cities.csv', 'r') as file:
    reader = csv.reader(file)
    headers = next(reader) # Read the header row
    
    data = []
    for row in reader:
        record = {}
        for i, value in enumerate(row):
            record[headers[i]] = value
        data.append(record)


Comments


Inchieh is both an idea and a learning challenge for us (and of course for anyone who wants to be with us). The purpose of the idea can be seen from its name. You are supposed to say what each picture is. فارسی