Reading a csv file as a dictionary with Python (انتشار: 1402/07/09)

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)


نظرات خوانندگان نوشته


نظری در این مورد دارید؟ خوشحال می‌شیم اون رو برامون ارسال کنید.

Reading a csv file as a dictionary with Python

این چیه هم یه ایده است و هم یه چالش یادگیری برای ما (و البته برای هر کسی که بخواد کنارمون باشه). هدف ایده از اسمش پیداس. قراره هر تصویری دادین بگه چیه.

English


پایتون مقدماتی