Python has a csv module that contains all sorts of utility functions to manipulate CSV files like conversion, reading, writing, and insertion. To convert a CSV File into a dictionary, open the CSV file and read it into a variable using the csv function reader() , which will store the file into a Python object.
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record.
Creating a Dictionary In Python, a dictionary can be created by placing a sequence of elements within curly {} braces, separated by 'comma'. Dictionary holds pairs of values, one being the Key and the other corresponding pair element being its Key:value.
I believe the syntax you were looking for is as follows:
import csv
with open('coors.csv', mode='r') as infile:
reader = csv.reader(infile)
with open('coors_new.csv', mode='w') as outfile:
writer = csv.writer(outfile)
mydict = {rows[0]:rows[1] for rows in reader}
Alternately, for python <= 2.7.1, you want:
mydict = dict((rows[0],rows[1]) for rows in reader)
Open the file by calling open and then using csv.DictReader.
input_file = csv.DictReader(open("coors.csv"))
You may iterate over the rows of the csv file dict reader object by iterating over input_file.
for row in input_file:
print(row)
OR To access first line only
dictobj = csv.DictReader(open('coors.csv')).next()
UPDATE In python 3+ versions, this code would change a little:
reader = csv.DictReader(open('coors.csv'))
dictobj = next(reader)
import csv
reader = csv.reader(open('filename.csv', 'r'))
d = {}
for row in reader:
k, v = row
d[k] = v
This isn't elegant but a one line solution using pandas.
import pandas as pd
pd.read_csv('coors.csv', header=None, index_col=0, squeeze=True).to_dict()
If you want to specify dtype for your index (it can't be specified in read_csv if you use the index_col argument because of a bug):
import pandas as pd
pd.read_csv('coors.csv', header=None, dtype={0: str}).set_index(0).squeeze().to_dict()
You have to just convert csv.reader to dict:
~ >> cat > 1.csv
key1, value1
key2, value2
key2, value22
key3, value3
~ >> cat > d.py
import csv
with open('1.csv') as f:
d = dict(filter(None, csv.reader(f)))
print(d)
~ >> python d.py
{'key3': ' value3', 'key2': ' value22', 'key1': ' value1'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With