I am trying to create a dictionary from a CSV file. The first column of the csv file contains unique keys and the second column contains values. Each row of the csv file represents a unique key, value pair within the dictionary. I tried to use the csv.DictReader and csv.DictWriter classes, but I could only figure out how to generate a new dictionary for each column. I want one dictionary. Here is the code I am trying to use:
def read_data(file_name):
data = {}
with open(file_name, "r") as f:
reader = csv.reader(f, delimiter = ',')
number_columns = len(next(reader))
for d in range (number_columns):
column_data, column_name = read_column(file_name, d)
data[column_name] = column_data
return data
My data: enter image description here My expected result: enter image description here
CodePudding user response:
If you don't mind having a 2D table for you data instead of key-value pairs, you can use the pandas module and in the module is useful funcion called to_dict() that converts a CSV to a dictonary. So this is how an example would look like:
import pandas as pd
file = pd.read_csv(filename, sep=',') #<---- the sep arguement does the same thing as the delimiter arguement, it is short for seperater
random_dict = pd.to_dict(file)
CodePudding user response:
Using csv DictReader
:
with open(file_name) as csv_file:
dictR = csv.DictReader(csv_file)
data = {hdr: [] for hdr in dictR.fieldnames}
for row in dictR:
for field in row:
data[field].append(row[field])
Build initial data
dict
using the field names fetched from the DictReader
. Then iterate over rows and fields in row. For each field append the field value to the list corresponding to the field name in the data
dict
.