python csv to dictionary code example
Example 1: python dictionary to csv
import csv
csv_columns = ['word','matchin']
csv_file = "found.csv"
try:
with open(csv_file, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
writer.writeheader()
for data in corpus:
writer.writerow(data)
except IOError:
print("I/O error")
Example 2: python csv dict reader
>>> import csv
>>> with open('names.csv', newline='') as csvfile:
... reader = csv.DictReader(csvfile)
... for row in reader:
... print(row['first_name'], row['last_name'])
...
Eric Idle
John Cleese
>>> print(row)
{'first_name': 'John', 'last_name': 'Cleese'}
Example 3: read csv and store in dictionary python
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}
Example 4: how to read a csv file and create a dictionary in c#
private Dictionary<string, string> ReadCsvFile(string pathToCsvFile)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
using (var reader = new StreamReader(pathToCsvFile))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line == null) continue;
var values = line.Split(';');
dictionary.Add(values[0],values[1]);
}
}
return dictionary;
}
// or
var dict = File.ReadLines(pathToCsvFile).Select(line => line.Split(';')).ToDictionary(line => line[0], line => line[1]);
Example 5: python create dictionary from csv
mydict = {y[0]: y[1] for y in [x.split(",") for x in open('file.csv').read().split('\n') if x]}
Example 6: how to create dictionary in python from csv
input_file = csv.DictReader(open("coors.csv"))