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 rep
If you have:
Do this:
mydict = {y[0]: y[1] for y in [x.split(",") for x in open('file.csv').read().split('\n') if x]}
It uses list comprehension to split lines and the last "if x" is used to ignore blank line (usually at the end) which is then unpacked into a dict using dictionary comprehension.
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'}
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)
You can also use numpy for this.
from numpy import loadtxt
key_value = loadtxt("filename.csv", delimiter=",")
mydict = { k:v for k,v in key_value }
Assuming you have a CSV of this structure:
"a","b"
1,2
3,4
5,6
And you want the output to be:
[{'a': '1', ' "b"': '2'}, {'a': '3', ' "b"': '4'}, {'a': '5', ' "b"': '6'}]
A zip function (not yet mentioned) is simple and quite helpful.
def read_csv(filename):
with open(filename) as f:
file_data=csv.reader(f)
headers=next(file_data)
return [dict(zip(headers,i)) for i in file_data]
Try to use a defaultdict
and DictReader
.
import csv
from collections import defaultdict
my_dict = defaultdict(list)
with open('filename.csv', 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
for line in csv_reader:
for key, value in line.items():
my_dict[key].append(value)
It returns:
{'key1':[value_1, value_2, value_3], 'key2': [value_a, value_b, value_c], 'Key3':[value_x, Value_y, Value_z]}