How can Python convert a CSV to a dictionary?

You can convert a CSV file into a dictionary by using the csv module and the DictReader class. Here is an example code:

import csv

def csv_to_dict(file_path):
    result = []
    with open(file_path, 'r') as file:
        reader = csv.DictReader(file)
        for row in reader:
            result.append(row)
    return result

# 用法示例
file_path = 'data.csv'  # 替换为你的CSV文件路径
data = csv_to_dict(file_path)
print(data)

In this example, the csv_to_dict function will open the specified CSV file and read it using the DictReader class. Each row will be converted into a dictionary where the column headers become the dictionary keys and the corresponding values become the dictionary values. All the dictionaries will be stored in a list and returned at the end.

bannerAds